【发布时间】:2012-02-10 13:52:20
【问题描述】:
编辑:已解决。一次将 DataTable 绑定到 DDL 的尝试意外发生了两次,而未检查页面的 PostBack 状态。一旦删除了多余的绑定尝试,问题就消失了。感谢大家的帮助。
我有一个 aspx 页面,其背后的一些代码具有下拉列表 (ddlLocationState) 或按字母顺序排列的美国各州。但是,无论选择什么项目,如果我做 ddlLocationState.SelectedItem/Value/Index 它总是“阿拉斯加”和“0”。每一次。即使在 SelectedIndexChange 事件处理程序中。
这里是在 aspx 页面中声明 DDL 的地方(这是页面中对它的唯一引用):
<tr>
<td> </td>
<td class="textBlue"><label>State: </label></td>
<td>
<asp:DropDownList runat="server" ID="ddlLocationState" style="width: 250px;"/>
</td>
</tr>
下面是设置 DDL 内容的代码: 私有 void BindStates()
private void BindDDL()
{
//Get all state info:
// Populate a DataTable called "sdt" with two columns, name (a state)
// and "id" (a number from 0 to 49)
//Bind the DataTable "sdt":
this.ddlLocationState.DataSource = sdt;
this.ddlLocationState.DataTextField = "name";
this.ddlLocationState.DataValueField = "id";
this.ddlLocationState.DataBind();
}
这是一些试图获取当前选定值的代码隐藏:
private void ddlLocationState_SelectedIndexChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("on index changed: " + dlLocationState.SelectedItem.Value.ToString());
}
这里是调用 BindDDL 的地方:
protected void Page_Load(object sender, EventArgs e)
{
this.pnlLocationMaintenance.Visible = false;
this.LocationSortDirection = "asc";
this.LocationSortField = "address";
this.BindStates();
this.dgLocations.CurrentPageIndex = 0;
this.BindLocations();
if (!Page.IsPostBack)
{
BindDDL();
}
ddlLocationState.SelectedIndexChanged += new EventHandler(ddlLocationState_SelectedIndexChanged);
}
为什么 ddlLocationState.SelectedItem/Value/Index 总是相同,即使在选定的索引更改事件处理程序中?
【问题讨论】:
-
您是否在页面加载时调用`BindDDL()`。如果是,那么请将其放入 if(!postBack) 中。问候
-
@Hayer 是的,我刚刚尝试过并看到相同的行为。此外,似乎选择索引更改甚至没有触发。我肯定已经在 Page_Load 中连接了这个事件......真的很奇怪。
-
贴出调用BindDDL的代码。
-
尝试删除
ddlLocationState_SelectedIndexChanged并在设计模式下双击下拉控件重新创建它。我希望它会起作用。