Monday, 7 May 2012

ItemDataBound in ASP.NET


The ItemDataBound event is raised after an item or row is data bound to the DataGrid control. This event provides you with the last opportunity to access the data item before it is displayed on the client. After this event is raised, the data item is nulled out and no longer available.

Within the method, we check if the current row is a header or a footer row.To do this we use ListItemType enumeration. ListItemType enumeration contains different types of items(header, footer, item, alternating item etc.)

To identify Header: if (e.Item.ItemType == ListItemType.Header)
To identify Footer: if (e.Item.ItemType == ListItemType.Footer)
To identify Item: if (e.Item.ItemType == ListItemType.Item)
To identify AlternatingItem: if (e.Item.ItemType == ListItemType.AlternatingItem)


ItemDataBound Function can be used for various functionalities:

How to hide any column of a particular row of a DataGrid?

procedure TClassName.dgrDataGrid_ItemDataBound(sender: System.Object; e: System.Web.UI.WebControls.DataGridItemEventArgs);
begin
   e.Item.Cells[‘ColumnName’].Attributes.Add('style','display:none');
end;


How to change contents of any column of a particular row of a DataGrid?

procedure TClassName.dgrDataGrid_ItemDataBound(sender: System.Object; e: System.Web.UI.WebControls.DataGridItemEventArgs);
begin
    if (e.item.ItemType =  listItemType.Item) or (e.item.ItemType =  listItemType.AlternatingItem) then
    begin
        if (e.Item.Cells[‘ColumnName’].Text = 'ABC') then e.Item.Cells[‘ColumnName’].Text := 'XYZ';
    end;
end;


How to change background color a particular row of a DataGrid?

procedure TClassName.dgrDataGrid_ItemDataBound(sender: System.Object; e: System.Web.UI.WebControls.DataGridItemEventArgs);
begin
    if (e.item.ItemType =  listItemType.Item) or (e.item.ItemType =  listItemType.AlternatingItem) then
    begin
        e.Item.Style['background'] := 'AliceBlue';                                  
        e.Item.Attributes.Item['OrigBackColor'] := 'AliceBlue'; //To retain the previous background color of the row
        //e.Item.BackColor := System.Drawing.Color.AliceBlue; This is the other way to color the background of the row.
    end;
end;


How to add javascript functions on each row of a DataGrid?

procedure TClassName.dgrDataGrid_ItemDataBound(sender: System.Object; e: System.Web.UI.WebControls.DataGridItemEventArgs);
begin
     if (e.item.ItemType =  listItemType.Item) or (e.item.ItemType =  listItemType.AlternatingItem) then
    begin
        e.Item.Attributes.Add('onselectstart', 'return OnSelectStartFunction();');
        e.Item.Attributes.Add('onclick',' return OnClickFunction();');
        e.Item.Attributes.Add('ondblclick',' return OnDoubleClickFunction();');
        e.Item.Attributes.Add('onmouseover','changeStyle();');
    end;
end;


In this way, you can use itemdatabound function to perform a lot of functionalities.

No comments:

Post a Comment