如何在textBox的onTextChange事件上更新dropDownList

时间:2013-09-05 17:54:04

标签: c# asp.net web

我有textBox名为txtDate

   <asp:TextBox ID="txtDate" runat="server" AutoPostBack="true" Width="120px" 
    ontextchanged="txtDate_TextChanged" ></asp:TextBox>

我还有dropDownList名为DropDownList1

    <asp:DropDownList ID="DropDownList1" runat="server" 
                DataSourceID="SqlDataSource2" DataTextField="sTime" DataValueField="sTime" 
                AutoPostBack="True">
    </asp:DropDownList>

DropDownList从名为SqlDataSource2的sqlDataSourse获取数据。 我需要在onTextChange的{​​{1}}事件上更新dropDownList。所以我写了这个。

textBox

但这不会更新 protected void txtDate_TextChanged(object sender, EventArgs e) { SqlDataSource2.SelectCommand = "NEW SQL COMMAND"; } 。如果有人可以,请帮助我。

4 个答案:

答案 0 :(得分:0)

我找到了。 我将TextChanged事件的代码更改为此。

     protected void txtDate_TextChanged(object sender, EventArgs e)
     {
          SqlDataSource2.SelectCommand = "NEW SQL COMMAND";
          DropDownList1.DataSourceID = "SqlDataSource2";
     }

答案 1 :(得分:0)

这里需要动态绑定。将下拉HTML更改为此

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
</asp:DropDownList> 

protected void txtDate_TextChanged(object sender, EventArgs e)
{

   /* This is not actual code but a kind of algorithm to proceed with*/

    using(SqlConnection con = new SqlConection(you_conn_string))
    {
       using (command)
       {
           usin(SqlDataReader rdr = cmd.ExecuteReader())
           {
               var dt = new Datatable();
               dt.load(rdr);
               dropdownlist1.datasource = dt;
               dropdownlist1.datatextfield="textfield";
               dropdownlist1.datavaluefield="valuefield";
               dropdownlist1.databind();

       }
     }
}

答案 2 :(得分:0)

SqlDataSource2.SelectCommand = "NEW SQL COMMAND";
DataView testView = (DataView)SqlDataSource2.Select(DataSourceSelectArguments.Empty);
DataTable table = testView .ToTable();

DropDownList1.Datasource = table;
DropDownList1.Databind();

答案 3 :(得分:0)

全局声明前四行,因此无需一次又一次地定义。

如果您使用此代码,请从dropdownlist .aspx代码中删除datatext,datavalue,datasourceID ..

protected void txtDate_TextChanged(object sender, EventArgs e)
{

  SqlConnection con = new SqlConection(you_conn_string)
  SqlCommand cmd=new SqlCommand();
  SqlDataAdapter da=new SqlDataAdapter();
  Dateset ds=new Dataset();
  cmd = new SqlCommand("procedure name to get data", con);  
  cmd.CommandType = CommandType.StoredProcedure;
  da = new SqlDataAdapter(cmd);
  da.Fill(ds);
  dropdownlist1.datasource = ds;
  dropdownlist1.datatextfield="textfield";
  dropdownlist1.datavaluefield="valuefield";
  dropdownlist1.databind();

}