下拉列表未返回正确的值

时间:2018-04-18 09:47:01

标签: c# asp.net sql-server

我遇到了一个问题,当我尝试检索下拉列表中某个项目的选定值时,它只会返回其中第一个项目的选定值。

这是我用来填充下拉列表中的代码,其中包含来自Sql-Server

中的表的数据
  protected void Page_Load(object sender, EventArgs e)
    {
        String Sql = @" select * from SupportTeam";
        SqlConnection conn = new SqlConnection(Properties.Resources.cString);
        SqlDataAdapter DA = new SqlDataAdapter(Sql, Properties.Resources.cString);          
        DataSet DS = new DataSet();
        DA.Fill(DS, "SupportTeam");
        DataTable DT = DS.Tables["SupportTeam"];


        DropDownList1.DataValueField = "supportTeamID";
        DropDownList1.DataTextField = "supportTeamName";
        DropDownList1.DataSource = DT;
        DropDownList1.DataBind();
}

当我加载Web表单时,一切正常,所有项目都显示在下拉列表中,但我遇到的问题是,当我在下拉列表中更改所选项目时,DataValueField保持不变

这是一个例子。我在Sql

中的表中有2行
  

SupportTeamID SupportTeamName

5         -         Marketing 

8         -         e-Learning

当我加载我的Web表单时,所选索引设置为0表示DataValueField为5.当我从下拉列表中选择e-Learning时,当我调试它时仍然说DataValueField是5时它应该是8。

以下是我用来在按钮点击事件中检索所选值的代码

  supportTeamID = Convert.ToInt32(DropDownList1.SelectedValue);

每次运行时,supportTeamID始终设置为5

我做错了什么或丢失了吗?提前致谢

1 个答案:

答案 0 :(得分:1)

你必须在代码不是IsPostBack

时编写代码
protected void Page_Load(object sender, EventArgs e)
{
    if(!IsPostBack)
    {
    String Sql = @" select * from SupportTeam";
    SqlConnection conn = new SqlConnection(Properties.Resources.cString);
    SqlDataAdapter DA = new SqlDataAdapter(Sql, Properties.Resources.cString);          
    DataSet DS = new DataSet();
    DA.Fill(DS, "SupportTeam");
    DataTable DT = DS.Tables["SupportTeam"];


    DropDownList1.DataValueField = "supportTeamID";
    DropDownList1.DataTextField = "supportTeamName";
    DropDownList1.DataSource = DT;
    DropDownList1.DataBind();
    }
}
相关问题