从asp.net中的下拉列表中获取选定的值
我有一个下拉列表,显示 aspx 文件中数据库中的国家/地区列表,
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();
}
}
这就是我调用此数据绑定列表的方式。
<asp:DropDownList ID="ddlCountry" runat="server"
DataTextField="printable_name"
DataValueField="iso">
</asp:DropDownList>
它显示列表,但如果我想选择第一个选项以外的选项,它总是插入值第一个选项从来没有选择过,我做错了什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,在访问所选值之前,数据源正在(重新)绑定到控件,因此所选值始终是数据源中的第一个值。
ShowCountries
在何时何地被调用?据猜测,我想说您在Page_Load
中缺少对IsPostback
的检查另外,我认为您不想调用
Dispose()< /code> 位于
finally
块中的ddlCountry
上。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
ShowCountries
get called? At a guess, I'd say you're missing a check forIsPostback
inPage_Load
Also, I don't think you want to call
Dispose()
onddlCountry
in thefinally
block.