如何从sqlserver检索数据到dropdownlist?

编程入门 行业动态 更新时间:2024-10-26 23:24:52
本文介绍了如何从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?

本文发布于:2023-10-28 23:49:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538122.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   sqlserver   dropdownlist

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!