datagrid| dynamic in applications, many times it is necessary to modify the rendering of the DataGrid after binding, such as
(1) When the data meet certain conditions need to modify its rendering mode
(2) Convert logical values in the database (0,1) into men and women to present and so on
There are roughly 2 ways to do this
(1) modifying values in ItemDataBound
(2) Use a function to worry about when binding
Similarly, the database is in accordance with http://blog.csdn.net/lovecherry/archive/2005/02/25/301441.aspx
Let's implement the following 2 features
(1) in the ItemDataBound to the age of less than 30 of the person's line of background change to pink
The code is as follows
private void Datagrid1_itemdatabound (object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{
if (e.item.itemtype==listitemtype.item| | e.item.itemtype==listitemtype.alternatingitem| | E.item.itemtype==listitemtype.edititem)
{
if (Convert.ToInt16 (DataBinder.Eval (e.Item.DataItem, "iage")) <30) E.item.backcolor=color.pink;
}
}
Of course you need to register the event
This. Datagrid1.itemdatabound + = new System.Web.UI.WebControls.DataGridItemEventHandler (this. Datagrid1_itemdatabound);
(2) The person whose name is "Zhu Ye", with the aggravated display
Front Code
<% #DataBinder. Eval (Container.DataItem, "VName")%>
Amended to
<%# MyFunc (DataBinder.Eval (Container.DataItem, "VName"))%>
Background code
Protected string MyFunc (object s)
{
String _s;
if (s.tostring () = = "Zhu Ye")
_s= "<b>" +s.tostring () + "</b>";
Else
_s=s.tostring ();
return _s;
}
The above 2 kinds of function is also I said above the roughly 2 kinds of methods to achieve the above operation
It's as simple as that.
For some of the other related extensions, I'm not going to elaborate.
For example, to change the properties of some controls based on a value:
If the control is in a template column, it can pass ((control type) E.item.findcontrol (ID)). Attribute = value to dynamically set;
If the control is not in a template column, it can pass ((control type) e.item.controls[index number]. property = value to dynamically set
You can also write statistics for other columns based on the values of one column, all the same
Action in the ItemDataBound event method, because the data is bound at this time