我有一个下拉列表"国家","城市"文本框和一个"添加"按钮。国家下拉列表不是强制性的,所以我可以添加一个没有国家的城市,添加一个空的"国家"到网格视图工作正常。问题是,当我点击网格视图中的"编辑"时,它将其绑定到列表中的第一个国家,它不只是显示一个空白:
<asp:DropDownList ID="DDLCountry" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="DDLCountry_SelectedIndexChanged" InitialValue="">
<asp:ListItem Text="------------------------ Select ------------------------" Value="" />
</asp:DropDownList>
<asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
<asp:Button ID="btnNewLList" runat="server" OnClick="btnNewLList_Click" Text="Add new Country"/>
<asp:GridView ID="gvAddNewCountry" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" OnRowCommand="gvAddNewCountry_RowCommand" OnRowDeleting="gvAddNewCountry_RowDeleting" OnRowDataBound="gvAddNewCountry_RowDataBound" OnRowUpdating="gvAddNewCountry_RowUpdating" OnRowEditing="gvAddNewCountry_RowEditing" OnRowCancelingEdit="gvAddNewCountry_RowCancelingEdit" ShowHeaderWhenEmpty="True">
<EmptyDataTemplate>
No Data
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Edit"/>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true">
</asp:CommandField>
<asp:TemplateField HeaderText="Country>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<% #Eval("Country") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DDCountry" runat="server" AppendDataBoundItems="True" AutoPostBack="false"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
代码隐藏:
Protected Sub gvAddNewCountry_RowCommand(sender As Object, e As GridViewCommandEventArgs)
If e.CommandName = "Edit" Then
Dim rowCountryToEdit As Integer = e.CommandArgument
Dim ddListCountry As DropDownList = (CType(gvAddNewCountry.Rows(CInt(e.CommandArgument)).FindControl("DDCountry"), DropDownList))
ddListCountry.DataSource = (From x In Country Where x.Domain = "lCountry" Order By x.Description Select x).ToList()
ddListCountry.DataTextField = "Description"
ddListCountry.DataValueField = "ID"
ddListCountry.DataBind()
End If
End Sub
谢谢你的帮助
1条答案
按热度按时间ajsxfq5m1#
好的,那么当你在gv行中有/想要一个ddl的时候呢?
我们需要两个步骤。
第一步:加载dll的选择列表
第二步:将ddl设置为当前行的值,如果当前行还没有值,则为空(没有选择)。这也意味着我们必须为dll获取当前行的值,并设置ddl以反映这个现有的选择。
这是一个两步的过程。
我们通常使用的“事件”是行绑定事件(listview、gridview等控件都有这个事件)。
另外,一个非常好的助手提示?在数据绑定事件期间(但仅在期间),您可以完全使用数据源中的所有列-即使列不在gv中!!!
我没有一个实体数据库第一次设置,你有,但让我们加载了一个组合框的gv:
所以,我们的女朋友:
我们要填充的代码是:
注意在上面,我创建了一个页面范围(类范围)的数据表rstRating.这在数据绑定之后会超出范围,但是我们只需要它在gv数据绑定操作期间持久存在(因为对于gv的每一行,我们不想一遍又一遍地运行查询-我们需要相同的dll选择列表).
好的,现在我们看到/得到:
我们需要做的只是加载dll,并为每一行设置它。我们使用RowDataBound事件。
所以,代码是这样的:
因此,对于每一行,获取dll。
对于该行,加载选项
然后,对于该行,将ddl设置为当前行值(但检查是否为空,不要设置-它将显示我们的“选择”选择值。