I have a class with all different kinds of data members, including a list of strings. When I bind the data to a GridView, I want to be able to separate out the list of strings into different columns in the GridView. These strings are more like flags, there is a ma开发者_如何学Pythonx of 3 flags. The list could be empty, if no flags apply, or it could contain only one or two flags. How can I separate out these flags into different GridView columns? Do I need to do it in the OnRowDataBound event?
Current, my aspx code looks something like this. I want to be able to change the ImageUrl of the Image controls based on if the flag is raised or not.
<asp:TemplateField HeaderText="Tax" SortExpression="Tax">
<ItemTemplate>
<asp:Image ID="imgTax" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compliance" SortExpression="Compliance">
<ItemTemplate>
<asp:Image ID="imgCompliance" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Accounting" SortExpression="Accounting">
<ItemTemplate>
<asp:Image ID="imgAccounting" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Thanks!
Is there any way for you to modify your data to turn these strings into booleans? Using strings in this way strikes me as a code smell. Personally, I would turn these strings into boolean properties of the class you're using as the data source for your grid and modify their visibility properties in the markup, rather than go back to the database to select these properties on a row-by-row basis.
Regardless of that, yes, you can use the RowDataBound event like this:
yourGrid_RowDataBound(object sender, EventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
YourClass currentClass = (YourClass) e.Row.DataItem;
for (int i = 0; i < currentClass.stringFlags.Length; i++)
{
string currentFlag = currentClass.stringFlags[i];
if (currentFlag == "Tax")
{
Image imgTax = (Image) e.Row.FindControl("imgTax");
imgTax.Visbile = true;
}
else if (currentFlag == "Compliance")
{
Image imgCompliance = (Image) e.Row.FindControl("imgCompliance");
imgCompliance.Visbile = true;
}
else if (currentFlag == "Accounting")
{
Image imgAccounting = (Image) e.Row.FindControl("imgAccounting");
imgAccounting.Visbile = true;
}
}
}
}
精彩评论