I have a dropdownlist which shows a list of countries from my database
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();
}
}
in the aspx file this is the way how I call this databounded list
<asp:DropDownList ID="ddlCountry" runat="server"
DataTextField="printable_name"
DataValueField="iso">
</asp:DropDownList>
It shows the list but if I want to select an option other then the first one it always inserts the value of the first option en never the selected one, what am I doing wrong ?
It sounds to me like the data source is being (re-)bound to the control before you are accessing the selected value, thus the selected value is always the first value in the datasource.
Where and when does
ShowCountriesget called? At a guess, I’d say you’re missing a check forIsPostbackinPage_LoadAlso, I don’t think you want to call
Dispose()onddlCountryin thefinallyblock.