CSharp Using Rowcreated Event To Programmatically Change Style – ADO.Net Database

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Using the RowCreated Event to programmatically change the style</title>
    <script runat="server">
        protected void gridProducts_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int daysToManufacture = (int)DataBinder.Eval(e.Row.DataItem, "DaysToManufacture");                if (daysToManufacture == 0)
                {
                    e.Row.BackColor = System.Drawing.Color.LightPink;
                    e.Row.ForeColor = System.Drawing.Color.Maroon;
                }
                else if (daysToManufacture == 1)
                {
                    e.Row.BackColor = System.Drawing.Color.LightCyan;
                    e.Row.ForeColor = System.Drawing.Color.DarkBlue;
                }
                else
                {
                    e.Row.BackColor = System.Drawing.Color.LightGray;
                    e.Row.ForeColor = System.Drawing.Color.Red;
                }
            }
        }       </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="productsSource" runat="server"
            ProviderName="System.Data.SqlClient"
            ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
            SelectCommand="Select ProductID, Name, ProductNumber, DaysToManufacture from Production.Product">
        </asp:SqlDataSource>
        <asp:GridView runat="server" ID="gridProducts" DataSourceID="productsSource"
            AutoGenerateColumns="false" OnRowCreated="gridProducts_RowCreated">
            <columns>
                <asp:BoundField DataField="ProductID" HeaderText="ID" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="ProductNumber" HeaderText="Number" />
                <asp:BoundField DataField="DaysToManufacture" HeaderText="Days To Manufacture" />
            </columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.