我有一张表格,用户可以填写3种不同的费用,然后点击勾选框并批准其中一项费用。然后需要在DataGrid
DataGrid的代码:
<asp:DataGrid CssClass="tblResults" runat="server" ID="dgDetails" OnItemDataBound="dgDetails_ItemDataBound" DataKeyField="ID" AutoGenerateColumns="false" style="display:none">
<HeaderStyle CssClass="tblResultsHeader" />
<AlternatingItemStyle BackColor="#EEEEEE" />
<Columns>
<asp:BoundColumn DataField="Code" HeaderText="Code"></asp:BoundColumn>
<asp:BoundColumn DataField="Cost" HeaderText="Cost"> </asp:BoundColumn>
<asp:HyperLinkColumn DataNavigateUrlFormatString="javascript:deleteDetail({0})" DataNavigateUrlField="ID" HeaderText="Delete" DataTextField="ID" ItemStyle-CssClass="tblRowDelete" ></asp:HyperLinkColumn>
</Columns>
代码背后:
protected void dgDetails_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer && e.Item.ItemType != ListItemType.Pager)
{
Quote.QuoteDetails qd = (Quote.QuoteDetails)e.Item.DataItem;
e.Item.Attributes.Add("ID", "dgDetails_" + qd.ID);
e.Item.Attributes.Add("class", "dgDetailsRow");
e.Item.ToolTip = "Click here to Edit Detail";
}
问题是在DataGrid
中显示正确的费用。现在它正在显示DataField Cost
。但是,如果第二个Cost
已获批准,那么我需要显示DataField Cost2
。有没有办法在DataGrid
中设置if语句来检查哪些费用已经批准?类似的东西:
if(approved1.checked)
{
<asp:BoundColumn DataField="Cost" HeaderText="Cost"> </asp:BoundColumn>
}
else if (approved2.checked)
{
<asp:BoundColumn DataField="Cost2" HeaderText="Cost"> </asp:BoundColumn>
}
可以在DataGrid
中添加if语句吗?或者有没有办法从后面的代码中做到这一点?
答案 0 :(得分:1)
我会使用背后的代码和模板列。
<asp:TemplateColumn>
<ItemTemplate>
<asp:Label ID="lblCost" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
代码背后类似于:
protected void dg1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
Label lblCost;
Quote.QuoteDetails qd = (Quote.QuoteDetails)e.Item.DataItem;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
lblCost = (Label)e.Item.FindControl("lblCost");
if (qd.Approved1)
lblCost.Text = string.Format("{0:0.00", qd.Cost);
else if (qd.Approved2)
lblCost.Text = string.Format("{0:0.00", qd.Cost2);
else
throw new NotImplementedException("oops!");
}
}