2017-07-26 58 views
0

我正在开发一个asp.net页面,其中两个DropDown列表填充来自数据库中相同表格的值,其中用户需要选择帐户名称和我希望第二个DropDown列表根据First下拉列表选择自动填充它自己的值(Acount Code),共享相同的帐户名称。下面是我的示例代码...如何基于asp.net中的选定文本框自动筛选DropDown列表值

<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(); 
        }  
       } 
      } 
     } 

就我而言,如果我更改帐户名称的价值观,帐户代码不会自动改变。我怎么能做到这一点..?谢谢

回答

0

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

1)当您在下拉菜单中选择一个项目时,Autopostback会导致回发。

2)OnSelectedIndexChanged是一个事件,您将不得不编码以填充第二个下拉菜单。

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