【问题标题】:Drop Down List not returning correct value下拉列表没有返回正确的值
【发布时间】:2018-04-18 09:47:00
【问题描述】:

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

这是我用 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 支持团队名称

5         -         Marketing 

8         -         e-Learning

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

这是我用来在按钮点击事件中检索到选定值的代码

  supportTeamID = Convert.ToInt32(DropDownList1.SelectedValue);

每次运行时,supportTeamID 总是设置为 5

我做错了什么或遗漏了什么?提前致谢

【问题讨论】:

  • 这段代码你在哪里写的?在 Form_Load 中?
  • 我写了表单加载的顶部代码和按钮点击事件中的选中值检索代码
  • 在这里发送您的代码

标签: c# asp.net sql-server


【解决方案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();
    }
}

【讨论】:

  • 是的,我只需要等4分钟哈哈哈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 1970-01-01
相关资源
最近更新 更多