如何在下拉列表中获取所选项目的值

问题描述:



我正在创建一个Web表单项目。我的页面中有下拉列表。我将它与数据库中的数据绑定。我已经设置了它的dataValuefield属性。现在,当我想从下拉列表中获取所选值时,我写了以下行。

Hi,
I am creating a web forms project. I have dropdownlist in my page. I am binding it with the data from database. I have set dataValuefield property of it. Now when I want to fetch the selected value from dropdownlist, I have written following line.

<pre lang="c#">
c_id = Convert.ToInt16(ddlClients.SelectedValue);





但是每次在c_id中,值都是0.在调试期间在SelectedValue中,正确的值存在。问题是什么?帮帮我。



But every time in c_id, value is 0. During debugging in SelectedValue, correct value is there. What is the problem? Help me.





不确定但看起来你绑定数据到ddlClients控件上每次回发,所以你每次都得到默认值。



请确保你第一次加载页面时,应该只将数据绑定到ddlClients控件一次 - b $ b

Hi,

Not sure but it looks you bind data to ddlClients control on every postback so you are getting default value every time here.

Please make sure you should bind data to ddlClients control only once when you load page first time as below -

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      // set datasource only first time page loads
      ddlClients.DataSource = "your data source";
      ddlClients.DataTextField = "property";
      ddlClients.DataValueField = "property";
      ddlClients.DataBind();
   }
}





现在你提供的代码似乎很好,当你访问除了ddlClients控件的选择更改事件。



但是如果要在选择更改时访问值,则需要确保AutoPostBack属性设置为True。 />


希望这会有所帮助。



Now the code you provided seems to be fine when you are accessing selected value other than the selection change event for ddlClients control.

But if you want to access value on selection change you need to make sure AutoPostBack property is set to "True".

Hope this helps.