【发布时间】:2016-09-21 06:58:23
【问题描述】:
我有一个从数据库中获取数据的网格视图。
这是 .NET 代码。有很多栏目,这里的模板是:Choice 就是我所说的那个。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" CellPadding="4" DataKeyNames="EmpID" ForeColor="#333333" GridLines="None" style="margin-right: 81px" Width="1174px" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Choice" SortExpression="Choice">
<EditItemTemplate>
<asp:DropDownList ID="DropDownChoice" Text='<%# Bind("Choice") %>' runat="server" Width="60px">
<asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblChoice" runat="server" Text='<%# Bind("Choice") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
在EditItemTemplate 上,用户可以编辑数据库中的上述数据。我可以使用下拉列表并将文本显示为 No 或 Yes,但将保存在数据库中的值仍然是 0 和 1。
<EditItemTemplate>
<asp:DropDownList ID="DropDownChoice" Text='<%# Bind("Choice") %>' runat="server" Width="60px">
<asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
运行后,我无法在 Gridview 上显示文本 No 和 Yes。如您所见,这里是 ItemTemplate 代码:
<ItemTemplate>
<asp:Label ID="lblChoice" runat="server" Text='<%# Bind("Choice") %>'></asp:Label>
</ItemTemplate>
请建议一种方式/方法,以便在执行后在 ItemTemplate/Gridview 部分显示 No/Yes。谢谢(如果您可能需要 C# 代码在 gridview 上绑定数据,请告诉我)
注意: 我已尝试在此question 中回答的 RowDataBound 事件。 这是代码:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;
if (dr["Choice"].ToString() == "0")
{
((Label)e.Row.FindControl("lblChoice")).Text = "No";
}
else if (dr["Choice"].ToString() == "1")
{
((Label)e.Row.FindControl("lblChoice")).Text = "Yes";
}
}
}
但它不起作用。我错过了什么吗?我必须在<ItemTemplate> 标签中包含一些内容吗?
【问题讨论】:
-
@iceDragon 我实际上已经尝试过那篇文章中的 RowDataBound 事件,但恐怕没有指出如何将其调用到 .Net 的答案?你知不知道怎么?谢谢(我也会编辑这个问题并包括这个)
-
像这样将事件添加到 GridView 工具
-
谢谢!可能我还需要 20 个声望,所以我可以对这个问题发表评论,询问我还需要添加什么,所以它只有 OnRowDataBound="GridView1_RowDataBound"
-
不客气,是的,就是这样,您在 gridView 标记中添加事件调用,然后编辑代码以满足您的要求。我认为您的代码应该运行顺畅。你还有什么问题吗?