locked
Setting GridView cell backcolor RRS feed

  • Question

  • User-1336852631 posted

    Has anyone found a way of applying conditional formatting to gridview cells.  For example set a cell to have a red backcolor if it's value is larger than the value in another cell.

    I know you can do this without dynamic data, but with dynamic data it's difficult to get at the values.

    Wednesday, July 18, 2012 6:57 AM

Answers

  • User350138131 posted

    I did try code similar to that, but e.Row.Cells(n).Text is always empty in a dynamic data site.

    protected void GV_RowDataBound(object sender, GridViewRowEventArgs e) {
    	if (e.Row.RowType == DataControlRowType.DataRow) {
    		int cellIndex = 2;
    		string dataField = ((DynamicField)((DataControlFieldCell)e.Row.Cells[cellIndex]).ContainingField).DataField;
    		Control dataControl = ((FieldTemplateUserControl)((DynamicControl)e.Row.Cells[cellIndex].FindDynamicControlRecursive(dataField)).FieldTemplate).DataControl;
    		string cellText = ((Literal)dataControl).Text; // ((TextBoxl)dataControl).Text; for Edit Mode
    	}
    }


    For FindDynamicControlRecursive() see http://csharpbits.notaclue.net/2009/01/dynamic-data-cascading-fieldtemplates.html

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 18, 2012 8:42 AM
  • User-330204900 posted

    HI Biga, see Conditional Row Highlighting in Dynamic Data on my blog :)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 18, 2012 8:45 AM
  • User-1336852631 posted

    This is what I ended up doing.  It uses Valz's code and some constants for the column index values.   There may be a better way but this works.  I didn't use an attribute in the end.  This seemed overkill as my requirement was specific to one page.

        static class Constants
        {
            public const int IndexOfColumnToCompare= 6;
            public const int HighlightColumn= 9;
        }
    
    ...
    
            protected void GridView1RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    int cellIndex = Constants.IndexOfColumnToCompare;
                    string dataField = ((DynamicField)((DataControlFieldCell)e.Row.Cells[cellIndex]).ContainingField).DataField;
                    Control dataControl = ((FieldTemplateUserControl) (DynamicControl)e.Row.Cells[cellIndex].FindDynamicControlRecursive(dataField)).FieldTemplate).DataControl;
                    string compareText= ((Literal) dataControl).Text; 
    
                    cellIndex = Constants.HighlightColumn;
                    dataField = ((DynamicField)((DataControlFieldCell)e.Row.Cells[cellIndex]).ContainingField).DataField;
                    dataControl = ((FieldTemplateUserControl)((DynamicControl)e.Row.Cells[cellIndex].FindDynamicControlRecursive(dataField)).FieldTemplate).DataControl;
                    string highlightText = ((Literal) dataControl).Text; 
    
                    if (Convert.ToDecimal(highlightText ) >= Convert.ToDecimal(compareText))
                    {
                        e.Row.Cells[cellIndex].CssClass = "RedBackground";
                    }
                }
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 19, 2012 6:24 AM

All replies

  • User-672832619 posted

    May be this will help you...

    Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim cell5Value As Integer = Convert.ToInt32(e.Row.Cells(5).Text)
                Dim cell2Value As Integer = Convert.ToInt32(e.Row.Cells(2).Text)
                 
                If cell5Value > cell2Value Then
                    e.Row.Cells(6).BackColor = System.Drawing.Color.Red
     
                Else
                    e.Row.Cells(6).BackColor = System.Drawing.Color.Green
                End If
         End If
    
    End Sub

    Wednesday, July 18, 2012 7:18 AM
  • User-1336852631 posted

    Hi 

    I did try code similar to that, but e.Row.Cells(n).Text is always empty in a dynamic data site.

    Wednesday, July 18, 2012 7:33 AM
  • User-672832619 posted

    Do u call any method in PageLoad event?

    Wednesday, July 18, 2012 7:42 AM
  • User-1336852631 posted

    My page_load is just the standard one for a List.aspx page:

            protected void Page_Load(object sender, EventArgs e)
            {
                Title = table.DisplayName;
    
    
                // Disable various options if the table is readonly
                if (table.IsReadOnly)
                {
                    GridView1.Columns[0].Visible = false;
                    InsertHyperLink.Visible = false;
                    GridView1.EnablePersistedSelection = false;
                }
    
                if (!table.CanInsert(Context.User))
                {
                    InsertHyperLink.Visible = false;
                }
            }



    Wednesday, July 18, 2012 8:06 AM
  • User-672832619 posted

    How you fill your grid can i have your code plz..?

    Wednesday, July 18, 2012 8:15 AM
  • User-1336852631 posted

    Hi,

    The List.aspx page_init method fills the data source as follows:

            protected void Page_Init(object sender, EventArgs e)
            {
                table = DynamicDataRouteHandler.GetRequestMetaTable(Context);
                //Restore the filter saved in the Custom Filter drop down list selection changed method.
                var defaultValues = Page.GetFilterValuesFromSession(table, table.GetColumnValuesFromRoute(Context));
                GridView1.SetMetaTable(table, defaultValues);
                
                GridDataSource.DomainServiceTypeName = table.DataContextType.AssemblyQualifiedName;
                GridDataSource.QueryName = table.GetSelectMethod();
    
                GridView1.ColumnsGenerator = new DefaultAutoFieldGenerator(table);
                GridView1.DataKeyNames = table.PrimaryKeyColumns.Select(c => c.Name).ToArray();
            }



    Wednesday, July 18, 2012 8:20 AM
  • User-672832619 posted

    Hello biga, as per my understanding your grid is filling with proper data but you are unable to set back color tperticular cell.

    Am i right?

    Wednesday, July 18, 2012 8:29 AM
  • User350138131 posted

    I did try code similar to that, but e.Row.Cells(n).Text is always empty in a dynamic data site.

    protected void GV_RowDataBound(object sender, GridViewRowEventArgs e) {
    	if (e.Row.RowType == DataControlRowType.DataRow) {
    		int cellIndex = 2;
    		string dataField = ((DynamicField)((DataControlFieldCell)e.Row.Cells[cellIndex]).ContainingField).DataField;
    		Control dataControl = ((FieldTemplateUserControl)((DynamicControl)e.Row.Cells[cellIndex].FindDynamicControlRecursive(dataField)).FieldTemplate).DataControl;
    		string cellText = ((Literal)dataControl).Text; // ((TextBoxl)dataControl).Text; for Edit Mode
    	}
    }


    For FindDynamicControlRecursive() see http://csharpbits.notaclue.net/2009/01/dynamic-data-cascading-fieldtemplates.html

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 18, 2012 8:42 AM
  • User-330204900 posted

    HI Biga, see Conditional Row Highlighting in Dynamic Data on my blog :)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, July 18, 2012 8:45 AM
  • User-1336852631 posted

    Hello biga, as per my understanding your grid is filling with proper data but you are unable to set back color tperticular cell.

    Am i right?

    Hi Keyur Shah,

    That's correct.  I can set the backcolor for all cells or cells in a particular column but I can't test the values in the cells within the GridView RowDataBound event as the cell Text appears to be always empty.

    Wednesday, July 18, 2012 9:27 AM
  • User-1336852631 posted

    For FindDynamicControlRecursive() see http://csharpbits.notaclue.net/2009/01/dynamic-data-cascading-fieldtemplates.html

    Thanks Valz, The FindDynamicControlRecursive is good and thanks for the code example (I missed that somehow when I first looked but it's very useful!)

    Wednesday, July 18, 2012 9:37 AM
  • User-1336852631 posted

    Thanks Steve - this seems the way to go.  As I need to compare the value in one column to another and then apply the formatting, I'll have to adapt it slightly.  I think there's enough there in your article and your other article that Valz posted to come up with the solution.

    Wednesday, July 18, 2012 9:51 AM
  • User-672832619 posted

    If your cell values appears to be empty then try this code..

    public void fillgrid()
        {
            con.Open();
            ds=new DataSet();
            string str = "Select * from empinfo";
            cmd = new SqlCommand(str, con);
            
            da=new SqlDataAdapter(cmd);
            da.Fill(ds,"empinfo");
    
            grdemp.DataSource=ds.Tables[0];
            grdemp.DataBind();
            con.Close();
    
        }
    
    
    
    public void grdupdating_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            
            
            int id = Int32.Parse(grdemp.DataKeys[e.RowIndex].Value.ToString());
    
            con.Open();
    
            string ename = ((TextBox)(grdemp.Rows[e.RowIndex].FindControl("txt_ename"))).Text;
            string eadd = ((TextBox)grdemp.Rows[e.RowIndex].FindControl("txt_eadd")).Text;
            string ecno = ((TextBox)grdemp.Rows[e.RowIndex].FindControl("txt_ecno")).Text;
            string edesc = ((TextBox)grdemp.Rows[e.RowIndex].FindControl("txt_edesc")).Text;
    
            string txtename = grdemp.Rows[e.RowIndex].Cells[2].Text.ToString();
            
            
            string t5 = grdemp.DataKeys[e.RowIndex].Value.ToString();
    
    
            string str=" update empinfo set ename='"+ename+"',eadd='"+eadd+"',ecno='"+ecno+"',edesc='"+edesc+"' WHERE eid = '"+id+"'";
            cmd = new SqlCommand(str, con);
            cmd.ExecuteNonQuery();
            con.Close();
            lblmsg.Text = "Record had been updated..!!";
            con.Close();
            grdemp.EditIndex = -1;
            fillgrid();
    
        }
    

    Thursday, July 19, 2012 12:24 AM
  • User-1336852631 posted

    Hi Keyur Shah,

    I think the difference is, I'm using dynamic data, so can't find the controls in the way you have in your example.

    Thanks

    Thursday, July 19, 2012 4:02 AM
  • User-1336852631 posted

    This is what I ended up doing.  It uses Valz's code and some constants for the column index values.   There may be a better way but this works.  I didn't use an attribute in the end.  This seemed overkill as my requirement was specific to one page.

        static class Constants
        {
            public const int IndexOfColumnToCompare= 6;
            public const int HighlightColumn= 9;
        }
    
    ...
    
            protected void GridView1RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    int cellIndex = Constants.IndexOfColumnToCompare;
                    string dataField = ((DynamicField)((DataControlFieldCell)e.Row.Cells[cellIndex]).ContainingField).DataField;
                    Control dataControl = ((FieldTemplateUserControl) (DynamicControl)e.Row.Cells[cellIndex].FindDynamicControlRecursive(dataField)).FieldTemplate).DataControl;
                    string compareText= ((Literal) dataControl).Text; 
    
                    cellIndex = Constants.HighlightColumn;
                    dataField = ((DynamicField)((DataControlFieldCell)e.Row.Cells[cellIndex]).ContainingField).DataField;
                    dataControl = ((FieldTemplateUserControl)((DynamicControl)e.Row.Cells[cellIndex].FindDynamicControlRecursive(dataField)).FieldTemplate).DataControl;
                    string highlightText = ((Literal) dataControl).Text; 
    
                    if (Convert.ToDecimal(highlightText ) >= Convert.ToDecimal(compareText))
                    {
                        e.Row.Cells[cellIndex].CssClass = "RedBackground";
                    }
                }
            }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 19, 2012 6:24 AM