从asp.net的下拉列表中获取选定的值

时间:2010-11-21 13:47:31

标签: c# drop-down-menu

我有一个下拉列表,显示了我的数据库中的国家/地区列表

public void ShowCountries()
    {
        OdbcConnection conn;
        conn = new OdbcConnection(ConfigurationManager.ConnectionStrings["jConnString"].ConnectionString);
        conn.Open();
        string sql = "SELECT iso,printable_name FROM country";

        OdbcCommand cmd = new OdbcCommand(sql, conn);


        try
        {
            //ddlCountry.DataSourceID = "country";
            ddlCountry.DataSource = cmd.ExecuteReader();
            ddlCountry.DataTextField = "printable_name";
            ddlCountry.DataValueField = "iso";
            ddlCountry.DataBind();
        }
        catch (Exception ex)
        {
            Check.Text = "3" + ex.Message;
        }
        finally
        {
            ddlCountry.Dispose();
            conn.Close();
            conn.Dispose();
        }

    }

在aspx文件中,这就是我调用这个数据库列表的方式

    <asp:DropDownList ID="ddlCountry" runat="server" 
DataTextField="printable_name" 
DataValueField="iso">
    </asp:DropDownList>

它显示了列表,但是如果我想选择其他选项,那么它总是插入第一个选项的值而不是选择的那个,我做错了什么?

1 个答案:

答案 0 :(得分:0)

在我看来,在访问所选值之前,数据源正在(重新)绑定到控件,因此所选值始终是数据源中的第一个值。

ShowCountries何时何地被召唤?我猜你错过了IsPostbackPage_Load的支票

if (!IsPostback) {
    // bind the datasource here, when the page initially loads
    ShowCountries();
}

另外,我认为您不想在Dispose()区块中的ddlCountry上致电finally

相关问题