Saturday, January 30, 2010

Conditional Formatting on GridView

In this post i'll show you how we can do conditional formatting on GridView Web Server Control.

Suppose we want to change the background of all the rows having country as "India" to Blue.

Firstly, This is the Sql Table Structure:



Create a New Website by clicking File->New Website.

Then,

Add a connection String to the Web.config file

Then, Add a GridView to the .aspx page and change the DataKeyNames attribute to the ID Column

Now, In the Code Behind file

Add a class level variable to store Connection String and in the pageload event retrieve the connection string that we stored in the web.config file. For eg:

    static string constring;
    protected void Page_Load(object sender, EventArgs e)
    {
        constring = ConfigurationManager.ConnectionStrings["myConn"].ConnectionString;
        BindData();
    }
    protected void BindData()
    {
        using (SqlConnection con = new SqlConnection(constring))
        {
            con.Open();
            SqlDataAdapter adap = new SqlDataAdapter("Select * from MyCustomers", con);
            DataSet ds = new DataSet();
            adap.Fill(ds, "MyCustomers");
            GridView1.DataSource = ds.Tables[0];
            GridView1.DataBind();
        }
    }

In the RowCreated event of the Grid View add the following code:
   protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView gridrow = (DataRowView)e.Row.DataItem;
            string sex = Convert.ToString(gridrow["Country"]);
            if (sex.Trim() == "India")
            {
                e.Row.BackColor = System.Drawing.Color.LightBlue;
            }
        }
    }

And run the Web site, Output will be shown like this

No comments:

Post a Comment