如果控件里的项是在程序运行中动态绑定的,那么在用DropDownList.SelectedValue或者 DropDownList.SelectedItem.Value取值的时候,取得的数据总是第一项的数据,这是为什么呢?
找了半天,终于在CSDN的论坛里面搜到了答案,原来在程序运行过程中,因为DropDownList的项被再一次重新绑定,而起 SelectedIndex被初始化为了默认的0,所以,取得的值自然总是0了,解决的办法就是,把DropDownList数据绑定的代码放在!IsPostBack中,如下
if(!IsPostBack)
{
//绑定数据
}
还有一个问题就是,必须将DropDownList的enabelViewState设置为true,否则将不会得到任何值。
代码使用如下:
1、aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
ArrayList dept = new ArrayList();
dept.Add("迎泽");
dept.Add("万柏林");
dept.Add("小店");
dept.Add("杏华岭");
dept.Add("尖草坪");
dept.Add("清徐");
dept.Add("古交");
dept.Add("晋源");
dept.Add("娄烦");
if (!IsPostBack)
{
MyListBox.DataSource = dept;
MyListBox.DataBind();
}
}
myCommand.Parameters.Add(new SqlParameter("@wbjbxx_area", SqlDbType.VarChar, 50));
myCommand.Parameters["@wbjbxx_area"].Value = MyListBox.SelectedItem.Text;
2、aspx
<asp:DropDownList ID="MyListBox" runat="server" Height="23px" Width="108px">
</asp:DropDownList>