asp.net GridView replace Checkboxes with Yes/No in Dynamic GridView
I have a gridview that displays the results of a custom query. The number of columns is unknown, and whether or not the DataTable being bound contains boolean columns is unknown. The title of columns that will contain a boolean value is also unknown.
Without knowing that information beforehand, is there a way to开发者_如何学C be able to replace the checkboxes with a simple Yes/No ?
This seems quite straightforward with predefined columns, but not so much in this case.
I was able to come up with a solution not long after I posted the question. What I ended up doing is:
- Create a clone the DataTable with each column of type string,
- Iterate through each item array (object[]) to search for "True" and "False" and replace with "Yes" and "No", respectively,
- Create a new DataRow, set its ItemArray property to the new object array, and add the new DataRow to the new DataTable.
Here is the code of how it was done:
DataTable Clone = ResultsTable.Clone();
for (int i = 0; i < Clone.Columns.Count; i++)
{
Clone.Columns[i].DataType = typeof(string);
}
foreach (DataRow row in ResultsTable.Rows)
{
DataRow r = null;
object[] ItemArray = row.ItemArray;
for (int i = 0; i< ItemArray.Length; i++)
{
if (ItemArray[i].ToString() == "True") ItemArray[i] = "Yes";
if (ItemArray[i].ToString() == "False") ItemArray[i] = "No";
}
r = Clone.NewRow();
r.ItemArray = ItemArray;
Clone.Rows.Add(r);
}
This concept should be applicable to similar DataTable textual transformations as well.
精彩评论