Click here to Skip to main content
14,739,178 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am having the gridview as follows.. I need to change the row color based on the color value in db.

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
       SqlConnection Connection = new SqlConnection("conn string");
       SqlCommand Command1 = Connection.CreateCommand();
       Command1.CommandText = "Select colorId from table";
       using (SqlDataReader reader = Command1.ExecuteReader())
          while (reader.Read())
               colorId= reader["colorId"].ToString();
       SqlCommand com = new SqlCommand("gridcolor", Connection);
       com.CommandType = CommandType.StoredProcedure;
       com.Parameters.AddWithValue("@colorId", colorId);
       com.Parameters.Add("@color", SqlDbType.NVarChar, 30);
       com.Parameters["@color"].Direction = ParameterDirection.Output;
       string msg = (string)com.Parameters["@color"].Value;
           foreach (GridViewRow rows in GridView1.Rows)
              //here I need the condition to filter each rows with different color
              //  which I assigned in db
               GridView1.RowStyle.BackColor = System.Drawing.Color.FromName(msg);

//STORED PROCEDURE to get color using Id
CREATE proc [dbo].[gridcolor] @colorId bigint,@color nvarchar(40) output
select @colorstatusColor=color from status where colorId=@colorId
Updated 2-Apr-13 21:27pm
Maciej Los 3-Apr-13 3:33am
What are you trying to achieve? Do you want to set back color for row depending on values returned by query?
Janani Muthaiyan 3-Apr-13 3:34am
yes absolutely

Use GridViewRowEventArgs e passed into GridView1_RowDataBound procedure:
if (e.Row.RowType == DataControlRowType.DataRow)
            e.Row.BackColor = Color.FromName(StringValueReturnedByQuery);

But before... have a look at below SP:
CREATE proc [dbo].[gridcolor]
    @colorId bigint,
    @color nvarchar(40) output
    SELECT @color=color
    FROM status
    WHERE colorId=@colorId

    RETURN @color
Janani Muthaiyan 3-Apr-13 4:16am
@Maciej Los, Its getting the color from DB for the first time only..

OnDataRowBound Event you can set the color of row based on your condition.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            if (e.Row.RowType == DataControlRowType.DataRow)
                e.Row.Style.Add("background-color", "#000");

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900