对象接受方法不会填充下拉列表

时间:2016-12-03 16:00:30

标签: c# asp.net webforms

我有一个方法,我想多次使用,基本上填充下拉列表。

public void PopulateDropdown(string selectedValue, object listname)
{
    String connString = ConfigurationManager.ConnectionStrings["MySql"].ToString(); //Conn string
    MySqlConnection mySqlConnection = new MySqlConnection(connString); //Objekt
    MySqlCommand cmd = new MySqlCommand(); //cmd objekt

    cmd.CommandText = "SELECT NAME FROM CustomerDb WHERE CITY = \"" + selectedValue + "\"";
    cmd.CommandType = CommandType.Text;
    cmd.Connection = mySqlConnection;

    DropDownList dropDownList = listname as DropDownList;
    mySqlConnection.Open();

    dropDownList.DataSource = cmd.ExecuteReader();
    dropDownList.DataTextField = "NAME";
    dropDownList.DataBind();
    mySqlConnection.Close();
}

我的电话如下:

protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
    string value = DropDownList3.SelectedValue;
    PopulateDropdown(value, DropDownList4);
}

我知道我的电话和我的方法是正确的,但出于某种原因,我无法在DropDownList3_SelectedIndexChanged中调用它。 当我在DropDownList3中选择一个值时,它只会重新加载并选择默认值"选择城市"。

<asp:DropDownList ID="DropDownList3" CssClass="btn btn-default btn-md pull-right" runat="server" OnSelectedIndexChanged="DropDownList3_SelectedIndexChanged" AutoPostBack="true">
   <asp:ListItem>Select city</asp:ListItem>
   <asp:ListItem>City1</asp:ListItem>
   <asp:ListItem>City2</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList4" runat="server" CssClass="btn btn-default btn-md pull-right" OnSelectedIndexChanged="DropDownList4_SelectedIndexChanged" AutoPostBack="true" Style="">
</asp:DropDownList>

我的DropDownList3_SelectedIndexChanged看起来像这样:

protected void DropDownList3_SelectedIndexChanged(object sender, EventArgs e)
{
        string value = DropDownList3.SelectedValue;
        PopulateDropdown(value, DropDownList4);
}

回发在方法中没有达到断点。

2 个答案:

答案 0 :(得分:0)

我真的不知道这是否能解答您的问题,但是当从数据库中获取值并使用这些数据填充组合框或下拉列表时,我会使用此代码/查询:

    String path = "Data Source = LOCALHOST; Initial Catalog= sample_database; username='root'; password=''";
        MySqlConnection sqlcon = new MySqlConnection(path);
        MySqlCommand sqlcom = new MySqlCommand();
        MySqlDataReader sqlread;

        sqlcon.Open();
        sqlcom.CommandType = CommandType.Text;
        sqlcom.CommandText = "SELECT name from database_table where city = '"+TextBox1.text+"'";
        sqlcom.Connection = sqlcon;
        sqlread = sqlcom.ExecuteReader();
        while (sqlread.Read()) //use loop to get all data in the specified column
        comboBox1.Items.Add(sqlread[0].ToString()); //place the data gathered in the combobox or dropdownlist
        sqlcon.Close();

答案 1 :(得分:0)

可能是您在页面加载时填充城市列表,并且AutoPostBack会重新加载列表。见DropDownList's SelectedIndexChanged event not firing