Results 1 to 2 of 2

Thread: Attempting to Change Color of Datagrid Cells [C#]

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Posts
    308

    Question Attempting to Change Color of Datagrid Cells [C#]

    Given the following code [ds = dataset, dt = datatable, dg = datagrid];

    ds.Tables.Add(dt);
    DataGridTableStyle tableStyle = new DataGridTableStyle();
    tableStyle.MappingName = "0";
    int numCols = ds.Tables[0].Columns.Count;
    DataGridColoredTextBoxColumn aColumnTextColumn;
    for(int i = 0; i < numCols; ++i)
    {
    aColumnTextColumn = new DataGridColoredTextBoxColumn();
    aColumnTextColumn.HeaderText = ds.Tables[0].Columns[i].ColumnName;

    aColumnTextColumn.MappingName = ds.Tables[0].Columns[i].ColumnName;
    tableStyle.GridColumnStyles.Add(aColumnTextColumn);
    }

    DG.TableStyles.Clear();
    DG.TableStyles.Add(tableStyle);
    DG.DataSource = ds.Tables[0];
    }



    public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
    {
    protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
    {
    try
    {
    object o = this.GetColumnValueAtRow(source, rowNum);
    if( o!= null)
    {
    backBrush = new SolidBrush(Color.Aquamarine);
    foreBrush = new SolidBrush(Color.Blue);

    catch(Exception ex){ /* empty catch */ }
    finally
    {
    base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
    }
    }



    I saw this code posted in many forums and help pages so assumed it would be the best to use, all I want is to change the color of my Datagrid Cell if the value does not match a default value provided.

    This code is supposed to change all my Cells to the backBrush (aquamarine) and foreBrush (blue) however when I run the program nothing has changed [generates no errors either but Datagrid cells are all still black on white].

    Any clues what I am doing wrong?

    Note that my dataset [ds] is created dynamically by adding Rows/Columns, I am unsure about the “MappingName” and “ColumnName” properties [seeing as my ds was generated dynamically and not from a Database like SQL, all I did was .add Columns and .add Rows in For loops]

  2. #2

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Posts
    308
    Could it have something to do with my Datagrid being set to ReadOnly?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width