本文介绍了如何从sqlserver检索数据到dropdownlist?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨. 我打算将sqlserver中的表列插入dropdownlist中, 我的表(班)包括3个项目: 1-员工2-老师3-两者 为此,我使用了DataReader,如下所示:
Hi. i intend to insert a table column from sqlserver into the dropdownlist , my table(class)inlude 3 items:1-employee 2- teacher 3-both of them and for this matter i have used DataReader as below:
if (!IsPostBack) { using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["DBMarashi"].ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("select ClassId,ClassName from Class",conn); SqlDataReader dr = cmd.ExecuteReader(); SqlDataAdapter sad = new SqlDataAdapter(cmd); dr.Read(); ClassDrpDown.DataSource = dr; ClassDrpDown.DataTextField = "ClassName"; ClassDrpDown.DataValueField = "ClassId"; ClassDrpDown.DataBind(); } }但在调试以下代码后,在下拉列表中仅会出现2个项目: 2名老师中的3名,第3名在哪里?
but after i debug the following code , in dropdownlist only 2 items will appear: 2-teacher 3-both of them , where is the 3rd one ? and how can i retrieve it?
推荐答案您叫dr.Read,它读取第一个值.然后没有返回最后两个值,因此它们最终出现在您的放置列表中.删除该代码,这是完全错误的.使用SqlDateReader也是错误的,但是很显然,您只是在学习,因此可以根据需要进行尝试.不过,应该使用数据集. You called dr.Read, which read the first value. Then the last two values had not been returned, so they ended up in your drop list. Remove that code, it''s completely wrong. Using a SqlDateReader is also wrong, but, it''s clear you''re just learning, so play with it if you like. A dataset is what you should use, though.
试试这个: Hi, Try this: if (!IsPostBack) { using (SqlConnection conn =new SqlConnection(ConfigurationManager.ConnectionStrings["DBMarashi"].ConnectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand("select ClassId,ClassName from Class",conn); SqlDataAdapter sad = new SqlDataAdapter(cmd); DataTable dt = new DataTable() ; sad.Fill(dt); ClassDrpDown.DataSource = dt; ClassDrpDown.DataTextField = "ClassName"; ClassDrpDown.DataValueField = "ClassId"; ClassDrpDown.DataBind(); } }
--Amit
--Amit
更多推荐
如何从sqlserver检索数据到dropdownlist?
发布评论