如何选择和读取下拉列表中的数据? [英] how to select and read data in dropdownlist?
问题描述
你好.
我打算将我的dropdownlist绑定到sqlserver,并读取我在DB(Table City)中拥有的项目(CityName),然后列出并将其填充到dropdownlist中.
为此,我在Page_load中编写了以下代码,每当我开始调试所有要在dropdownlist中看到的城市项目时,该代码就会显示:
hello.
I intend to bind my dropdownlist to sqlserver and read the items(CityName)that i have them in DB(Table City)and then list and fill them into the dropdownlist.
for this matter i have written the code below in Page_load that whenever i start to debug all city items to be seen in dropdownlist:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["PersonTest"].ConnectionString;
conn.Open();
cmd.CommandText = "SELECT CityName FROM City";
cmd.Parameters.Add("@CityName", SqlDbType.NVarChar).Value = DropCity.AppendDataBoundItems;
cmd.ExecuteReader();
conn.Close();
}
但在(cmd.ExecuteReader();)行中会发生此错误:
InvalidOperationException未由用户代码处理.
ExecuteReader:连接属性尚未初始化
同时,我知道我可以使用ASP.net DataBinding(通过向导)功能,但是我想自己动手做.而且我也不知道哪种形式更适合使用?您建议使用哪一个?
but in line (cmd.ExecuteReader();) this error occurs:
InvalidOperationException was unhandled by user code.
ExecuteReader: Connection property has not been initialized
meanwhile i know that i can use ASP.net DataBinding(by wizard)ability, but i want to do it with myself . and also i don''t know which one is better to be used in forms? which one do you suggest to use?
推荐答案
您可以使用它来将数据绑定到您的下拉列表
Hi ,
you can use this for bind data to your dropdownlist
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PersonTest"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT CityName , id FROM City", conn))
{
DataTable dt = new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);
DropCity.DataTextField = "CityName";
DropCity.DataValueField = "id";
}
}
}
并选择下拉列表的值,您可以使用SelectedValue
最好的问候
米特瓦里(M.Mitwalli)
and for select the value of dropdownlist you can use SelectedValue
Best Regards
M.Mitwalli
这篇关于如何选择和读取下拉列表中的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!