【发布时间】:2016-07-08 13:42:47
【问题描述】:
我的 ASP.NET (VB) 页面上有一个详细信息视图,其中列出了客户的详细信息(他们的姓名、地址等)。
“国家/地区”选项是一个下拉列表,从数据库表中提取。查看详细信息视图时,这一切都很好,您可以看到他们所在的国家/地区。
但是,当我单击 DetailsView 上的 Edit 按钮时,下拉列表会正确显示 db 表中的所有可用国家,但它没有选择值,因此不是选择其当前设置的国家,而是默认值到列表的首位。这是错误的,因为它不是它们当前设置的值。
使用代码隐藏(VB),我应该如何将下拉列表的选定值设置为他们当前设置的国家名称?在代码隐藏中,我已经读取了他们当前的国家名称并将其存储在一个名为strCurrentCountryName的字符串变量中
例如。
Response.Write "strCurrentCountryName: " & strCurrentCountryName
将显示:
strCurrentCountryName: United Kingdom
所以我现在需要将他们的strCurrentCountryName 值与下拉列表中的一个国家/地区名称相匹配,并将其设置为他们的 SelectedValue。
我的代码在前面(列出了数据库中的所有国家/地区):
<asp:TemplateField HeaderText="Country" SortExpression="address5">
<EditItemTemplate>
<asp:SqlDataSource ID="SqlDataSourcecountryList" runat="server" ConnectionString="<%$ ConnectionStrings:PDConnectionString %>"
ProviderName="<%$ ConnectionStrings:PDConnectionString.ProviderName %>"
SelectCommand="SELECT country_name_short, country_name_long FROM country_list WHERE deleted = 0 ORDER BY country_name_long">
</asp:SqlDataSource>
<asp:DropDownList ID="DropDownListCountry" runat="server" CssClass="form-control"
DataSourceID="SqlDataSourcecountryList" DataTextField="country_name_long" DataValueField="country_name_short">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("address5") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
在代码隐藏中,我尝试了这个(在Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load 内):
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
这会给出以下错误消息:
'DropDownListCountry' is not declared. It may be inaccessible due to its protection level
我尝试使用这两行代码并将下拉列表放置在 EditItemTemplate 之外,并且效果很好:
DropDownListCountry.DataBind()
DropDownListCountry.Items.FindByText(strCurrentCountryName).Selected = True
果然,它确实正确地将他们的 Selected Value 设置为正确的国家/地区。
在我的代码隐藏 (vb) 中,我是否需要先以某种方式声明 DropDownListCountry?
当放置在我的 asp:TemplateField 的 EditItemTemplate 中时,如何使这项工作?
【问题讨论】: