RowDataBound: refer to cells by column name rather than index?

Last post 04-11-2008 3:32 PM by tmpuzer. 2 replies.

Sort Posts:

  • RowDataBound: refer to cells by column name rather than index?

    04-10-2008, 6:17 PM
    • Loading...
    • tmpuzer
    • Joined on 03-07-2008, 12:45 PM
    • Posts 315

     I have code like (this is just an example):

    protected void SomeGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
    
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
        e.Row.Cells[8].BackColor = System.Drawing.Color.Red;
      }
    }
     
     What I don't like about this is that I'm referring to the column I want by an index number.  If I change the number of columns in the gridview this breaks.  Is there a more robust way to refer to the column I want?
    If a post helps me I'll always eventually mark it as an answer. But I frequently don't mark it right away because I feel once a thread is marked as answered, discussion tends to end. And I like to discuss things a bit.
  • Re: RowDataBound: refer to cells by column name rather than index?

    04-10-2008, 8:34 PM
    • Loading...
    • aamador
    • Joined on 02-11-2008, 5:49 PM
    • Posts 1,105

    Not supported!  or at least this is not something you can do easily.  I would not say it is imposible because the column names are certainly there and you could create some sort of hack where you have enum which would still ref the cell id but use a name.  I can almost envision some code written in javascript to deal with this. You could look and see if anyone has extended the grid to have this type of name relationship. 

    Even better!  why don't you look into creating an extention of the GridView with that capability?

     

    I am not anti social, am just not user friendly
  • Re: RowDataBound: refer to cells by column name rather than index?

    04-11-2008, 3:32 PM
    Answer
    • Loading...
    • tmpuzer
    • Joined on 03-07-2008, 12:45 PM
    • Posts 315

    For the time being I'll just use a constant to avoid a magic number in my code:

    protected void SomeGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
      const int MY_COLUMN = 8;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
    e.Row.Cells[MY_COLUMN].BackColor = System.Drawing.Color.Red;
    }
    }

     

    If a post helps me I'll always eventually mark it as an answer. But I frequently don't mark it right away because I feel once a thread is marked as answered, discussion tends to end. And I like to discuss things a bit.
Page 1 of 1 (3 items)
Microsoft Communities
Page view counter