Making Links in GridView with AutoGenerateColumns = "True"

Sometimes, we need to leave the AutoGenerateColumns = true since, we don't know how many columns will be returned from the Database. Another technique is to use ITemplate interface and make your custom Template Columns during runtime. All the columns that are generated automatically are BoundColumns. Sometimes you want to display the column as a link which will open a new window. In the code below I have added the required HTML to the rows of the DataTable and later linked the bound the table to GridView control. Check out the following code snippet:

 foreach (DataRow r in userRows)
{                  
    
    distinctExamName = (
string)r["Name"] + "_" + r["UserID"].ToString();
   
 sb.Append("<a href='#'");
    sb.Append("onclick = '");
    sb.Append("DisplayExam(");
    sb.Append(Convert.ToInt32(r["UserID"]));
    sb.Append(","); 
    sb.Append(Convert.ToInt32(r["RoleID"])); 
    sb.Append(")'");
    sb.Append(">");
    sb.Append(r["Score"]);
    sb.Append("</a>");
    newRow[distinctExamName] = sb.ToString();
    sb = 
new StringBuilder();                                         
}

Even though you have attached the HTML to the row it will not be displayed as a link. For this, you can use the Row_DataBound event of the GridView control.

 protected void gvGrades_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        
if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView drv = (DataRowView)e.Row.DataItem;

            
for (int i = 0; i < drv.DataView.Table.Columns.Count; i++)
            {               
                
if (drv.ToString().IndexOf("<a") == 0)
                {
                    e.Row.Cells.Text = Server.HtmlDecode
                    (e.Row.Cells.Text);
                }                              
               
            }
        }
    }

Now, when the GridView is rendered you will see the links displayed in the column. I have attached a Java Script function to the link but you can pretty much do anything you desire.  

Thanks to webswapp for the tip.

powered by IMHO 1.3

Print | posted @ Sunday, April 23, 2006 8:18 PM

Twitter