2010-11-21 55 views
0

我有一个下拉列表,显示从我的数据库获取asp.net中选定值

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文件的国家名单,这是我如何把这个databounded列表

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

它显示列表,但如果我想选择一个选项,然后第一个它总是插入的第一个选项的价值en从来没有选择一个,我做错了什么?

+0

你如何在代码中选择一个选项? – 2010-11-21 13:49:59

回答

0

这听起来像数据源正在(重新)绑定到控件,然后再访问选定的值,因此选定的值始终是数据源中的第一个值。

何时何地ShowCountries被叫?在猜测,我会说你失踪了IsPostback检查中Page_Load

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

另外,我不认为你想在finally块调用Dispose()ddlCountry