Row Created Example

For this example I've used Northwind as backend and the table is products

Source:


<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" datakeynames="ProductID" datasourceid="SqlDataSource1" cellpadding="4" forecolor="#333333" gridlines="None" onselectedindexchanged="GridView1_SelectedIndexChanged" onrowcreated="GridView1_RowCreated">
<columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:boundfield datafield="ProductName" headertext="ProductName" sortexpression="ProductName">
<asp:boundfield datafield="CategoryID" headertext="CategoryID" sortexpression="CategoryID">
<asp:boundfield datafield="SupplierID" headertext="SupplierID" sortexpression="SupplierID">
<asp:boundfield datafield="QuantityPerUnit" headertext="QuantityPerUnit" sortexpression="QuantityPerUnit">
<asp:boundfield datafield="UnitPrice" headertext="UnitPrice" sortexpression="UnitPrice">
<asp:boundfield datafield="UnitsOnOrder" headertext="UnitsOnOrder" sortexpression="UnitsOnOrder">
</columns>
<rowstyle backcolor="#EFF3FB">
<footerstyle backcolor="#507CD1" bold="True" forecolor="White">
<pagerstyle backcolor="#2461BF" forecolor="White" horizontalalign="Center">
<selectedrowstyle backcolor="#D1DDF1" bold="True" forecolor="#333333">
<headerstyle backcolor="#507CD1" bold="True" forecolor="White">
<editrowstyle backcolor="#2461BF">
<alternatingrowstyle backcolor="White">
</asp:GridView>
<asp:sqldatasource id="SqlDataSource1" runat="server" connectionstring="">"
SelectCommand="SELECT [ProductID], [ProductName], [CategoryID], [SupplierID], [QuantityPerUnit], [UnitPrice], [UnitsOnOrder] FROM [Products]">
</asp:SqlDataSource>


Code behind page :

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Get Price from the row

decimal price;
price = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "UnitPrice"));

//Changing the cell color, by giving a condition

if (price > 50)
{
e.Row.BackColor = System.Drawing.Color.Blue;
e.Row.ForeColor = System.Drawing.Color.White;
e.Row.Font.Bold = true;
}
}
}


cheers

No comments: