Creating Gridview Columns Dynamically

Posted Wednesday, October 4, 2006 5:11 PM by C-Dog's .NET Tip of the Day

The gridview is pretty cool and can save you alot of time, but there are times when you need to add a gridview column dynamically. Say you have a hyperlink column that contains a filepath from your webconfig and you want the url of the hyperlink to use that filepath. One way to do this is in your Page_Load method get your filepath using Configuration Manager and the create the new column while adding to the DataNavigateUrlFormatString property.

// the DataNavigateUrlFields property requires and array even though I just have one item

string[] fieldArray = {"filename"};

// get u1a directory location from webconfig

string directoryLocation = ConfigurationManager.AppSettings["U1AStorageDirectoryLocation"];

// create a Sb object and append the strings needed
StringBuilder formattedString = new StringBuilder();
formattedString.Append(directoryLocation);
formattedString.Append("/{0}");

// create a HyperLink Column and add it to the GridView dynamically
HyperLinkField showFileColumn = new HyperLinkField();
showFileColumn.DataNavigateUrlFields = fieldArray;
showFileColumn.DataNavigateUrlFormatString = formattedString.ToString();
showFileColumn.Text = "Show File";
GridView1.Columns.Add(showFileColumn);

Kyle Kelin

Read the complete post at http://www.dotnettipoftheday.com/blog.aspx?id=304