Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datarepeater Databind 1

Status
Not open for further replies.

5679

Programmer
Feb 14, 2003
32
AU
Instead of using <%# DataBinder.Eval(Container.DataItem, "fieldname")%> in html, How can i bind data in C# itself, that is, without using the above line in html.
 
The DataGrid, DataList and Repeater controls each have an ItemDataBoundEvent. You add a handler for this event in your C# code, which executes each time an item is bound in the grid or list.

In that event handler, you get a reference to the DataItem currently being bound, and display one of it's properties.

Instead of the DataBinder.Eval code, just put a Label control in it's place (without any text value) and be sure to give it a meaningful ID.

Here's an example
Code:
In the .aspx file
<ItemTemplate>
    <asp:Label ID="lblFieldName" Runat="Server" />
</ItemTemplate>

Code:
//In your code-behind class

private void Reapeater1_ItemDataBound(object sender, RepeaterItemEventArgs e){

    //this won;t work on headers, footers, separators, etc.
    if(!(e.Item.ItemType==ListItemType.Item ||
        e.Item.ItemType==ListItemType.AlternatingItem))
           return;


    //get a reference to the data item
    DataRowView drv = (DataRowView)e.Item.DataItem;

    //get a reference to the label in the item
    Label lblFieldName = (Label)e.Item.FindControl("lblFieldName");

    //set it's Text value to the field in the datarow
    lblFieldName.Text = drv["FieldName"].ToString();
}

In order for this to work you will need to add the handler to the Repeater's ItemDataBound event. In Visual Studio, you can select the Repeater in Design View, go to the Events part of the properties window (lightning bolt icon), double click in the OnItemDataBound event and the method skeleton will automatically be added to the code behind, and the event wired up. You can check the OnInit method (the "Do not modify this section with the code editor" area) to see for yourself.

If you don't have Visual Studio, just add
Code:
OnItemDataBound="Repeater1_ItemDataBound"
to the Repeater tag, and make that method protected instead of private.

Greetings,
Dragonwell
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top