【问题标题】:How to automatically filter a DropDown List values based on selected textbox in asp.net如何根据asp.net中的选定文本框自动过滤下拉列表值
【发布时间】:2017-07-27 06:17:24
【问题描述】:

我正在开发一个 asp.net 页面,其中包含两个下拉列表填充数据库中同一个表中的值,其中用户需要选择帐户名称,我希望第二个下拉列表自动填充它自己的值(帐户代码) 基于第一个下拉列表选择共享相同的帐户名称。这是我的示例代码...

<span class="label">
  <asp:Label ID="Label2" runat="server" Text="Account Name"</asp:Label>
</span>
  <asp:DropDownList ID="name" runat="server"></asp:DropDownList><br />
<span class="label">
  <asp:Label ID="Label3" runat="server" Text="Account Code"></asp:Label>
</span>
<asp:DropDownList ID="code" runat="server"></asp:DropDownList>

我的 C# 代码如下..

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string CS = ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
                using (SqlConnection conn = new SqlConnection(CS))
                {
                    SqlCommand comm = new SqlCommand("SELECT AccountName, AccountCode FROM Account", conn);
                    conn.Open();

                    name.DataSource = comm.ExecuteReader();
                    name.DataTextField = "AccountName";
                    name.DataValueField = "AccountName";
                    name.DataBind();
                    conn.Close();

                    if(name.Text != null)
                    {
                        conn.Open();
                        SqlCommand com = new SqlCommand("SELECT AccountCode FROM Account WHERE AccountName= '" + name.Text +"'", conn);
                        code.DataSource = com.ExecuteReader();
                        code.DataTextField = "AccountCode ";
                        code.DataValueField = "AccountCode ";
                        code.DataBind();
                    }    
                }
            }
        }

在我的情况下,如果我更改帐户名称的值,帐户代码不会自动更改。我怎样才能做到这一点..?谢谢

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    为了满足您的要求,您必须在第一个下拉列表中添加两个属性 (1)“AutoPostBack”和 (2)“OnSelectedIndexChanged”。

    1) 当您在下拉列表中选择一个项目时,自动回发将导致回发。

    2) OnSelectedIndexChanged 是您必须编写代码以填充第二个下拉列表的事件。

    <asp:DropDownList ID="name" runat="server" AutoPostBack="true" OnSelectedIndexChanged="name_SelectedIndexChanged"></asp:DropDownList>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 2023-03-18
      • 1970-01-01
      • 2017-08-10
      • 2020-03-14
      • 2020-10-16
      • 1970-01-01
      相关资源
      最近更新 更多