How To: Change the row Background color based on the database value using GridView Control
We have seen many examples on how to change the background color of row based on the data using DataGrid Control. This can be done using a helper function or using the appropriate event of the datagrid
We will use the similar scenerio to find out how to use GridView Control in such case.
Step 1: Drag Drop GridView Control
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" ></asp:GridView>
Step 2: We will use SqlDataSource control for the connectivity with the Sql Database
Lets use web.config for Sql Connection string:
<connectionStrings>
connectionStrings><add name="DummyDB" connectionString="Server=localhost;Integrated Security=True;Database=DummyDB;Persist Security Info=True" providerName="System.Data.SqlClient" /> </connectionStrings >
</connectionStrings >
The connection string is used with the Sql Datasource control as follows in the respective page
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DummyDB %>" SelectCommand="Select * from products"></asp:SqlDataSource> Step 3: We have Products table with field Unitprice as one of the fields. We will change the row background color to red if the UnitPrice<10
Step 3: We have Products table with field Unitprice as one of the fields. We will change the row background color to red if the UnitPrice<10
This is done using the RowDataBound event
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" >
</asp:GridView>
Step 4: We will code as follows for the RowDataBound Event.
VB.NET
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)If e.Row.RowType = DataControlRowType.DataRow Then
If (e.Row.DataItem("UnitsInStock") < 20) Then
e.Row.BackColor = Drawing.Color.Red
End If
End If
End Sub
Thats All!