【问题标题】:Binding DropDownList using code behind in asp.net使用 asp.net 中的代码绑定 DropDownList
【发布时间】:2013-06-14 02:06:06
【问题描述】:

数据绑定仅在页面第一次加载时有效,否则无效。在我的页面的某个地方,我更新并插入了一些新的“名称”,我想在下拉列表中显示新添加的名称。但是如果我重新加载页面,那么新添加的名称将出现在下拉列表中。如何刷新下拉列表中的项目?我认为我的代码应该可以工作。请帮忙。谢谢

 private void RefreshDropDown()
    {
        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
        SqlConnection con2 = new SqlConnection(strConnString);
        SqlDataAdapter sda = new SqlDataAdapter();
        SqlCommand cmd1 = new SqlCommand("SELECT DISTINCT [Name] FROM [Main] order by Name asc");

        cmd1.Connection = con2;
        con2.Open();
        DropDownList1.DataSource = cmd1.ExecuteReader();
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "Name";
        DropDownList1.DataBind();
        con2.Close();

}

【问题讨论】:

  • 您不想在下拉列表中显示新添加的项目吗?你说当你重新加载页面时,名称会出现在列表中
  • DropDownList1.Items.Clear();
  • 你在页面生命周期中的哪个事件调用这个?
  • 请发布您的所有代码、标记和代码隐藏。
  • 这意味着当它不是回发时,您只需绑定页面加载中的项目,因此您应该将其更改为始终这样做。无论如何发布您的代码,以便我们可以写下您的答案

标签: c# asp.net


【解决方案1】:

我假设您有某种按钮可以插入新名称。 因此,在您完成插入/更新新名称后,单击此按钮添加对 RefreshDropDown() 的调用。 这应该可以解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 2010-09-13
    • 1970-01-01
    相关资源
    最近更新 更多