ASP.NET DropDownList问题

时间:2009-09-07 10:51:08

标签: c# asp.net mysql

[...]
public DataSet ReturnPromoMagazinesDs()
{

    MySql.Data.MySqlClient.MySqlConnection mysqlConnection = new MySql.Data.MySqlClient.MySqlConnection(this.connectionString);

    MySql.Data.MySqlClient.MySqlCommand mysqlCommand = new MySql.Data.MySqlClient.MySqlCommand("SELECT id, magazine_name FROM `magazines`", mysqlConnection);

    MySql.Data.MySqlClient.MySqlDataAdapter mysqlAdaptor = new MySql.Data.MySqlClient.MySqlDataAdapter(mysqlCommand);

    DataSet ds = new DataSet();

    mysqlAdaptor.Fill(ds, "magazines");

    return ds;
}

[...]
protected void Page_Load(object sender, EventArgs e)
{
        DataSet ds = new DataSet();
        ds = coreObject.ReturnPromoMagazinesDs();

        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = ds.Tables["magazines"].Columns["magazine_name"].ColumnName;
        DropDownList1.DataValueField = ds.Tables["magazines"].Columns["id"].ColumnName;
        DropDownList1.DataBind();

}

[...]
<asp:dropdownlist id="DropDownList1" runat="server"></asp:dropdownlist>

上面的代码工作正常,直到我获取 DropDownList1.SelectedValue ,它总是1(表中的第一个值)。表中的值不是这个的责任,如果我手动将项添加到DropDownList,一切正常。是什么导致这个?

2 个答案:

答案 0 :(得分:2)

当您在Page_Load方法中包装以下所有代码时,它是否正常工作:

if (!IsPostBack) { /* Code as in the original post */ }

答案 1 :(得分:0)

不确定某些内容是否会在翻译中丢失,但您可以简化以下行,即使它无法解决问题。

DropDownList1.DataTextField = "magazine_name";

DropDownList1.DataValueField = "id";