views:

174

answers:

2

my problem: how do I populate extra cells in my gridview during the runtime construction of the grid? (these cells are not bound to any datasource and all I want to do is show some custom text)

I have a gridview on my page and I get 2 columns as bound columns from a fixed database - let's call them

id and URL

I've added a couple of extra columns which are not bound to any datafield but I want to populate the cells with some text which is relevant to the id

for e.g. if the row 1 is

12 http://www.something.com

then I want the extra cell to have 'you have visited this 13 times'

12 http://www.something.com 'you have visited this 13 times'

this text comes from some internal processing I do.

What I want to do is to insert this text when the gridview is being constructed at run time..am totally clueless how to do this. I'm sorry if I'm asking a very dumb question..

+1  A: 

You can use the OnRowDataBound event of the GridView to get the current DataItem's content and then set the value of your extra column. You could also just get the cell's content. I think using the DataItem is a bit better, but you can do either.

Something like below

protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
       string myValue = e.Row.Cells[0].Text;
       e.Row.Cells[3].Text = " you have visited this " + myValue + " times";
       -- or --
       MyObjectType myData = e.Row.DataItem as MyObjectType ;
       Literal litText = e.Row.FindControl("litText") as Literal;
       litText.Text = "you have visited this " + myData.PropertyName + " times";
    }
}
Jim W
Thanks, Madcolor, Jim, that was most helpful. Still wading thru ASP.NET...