如何设置列表框从数据库中选择的项目? [英] How to set a Listbox selected items from database?

查看:192
本文介绍了如何设置列表框从数据库中选择的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Web应用程序中设计一个编辑页面.我的表单中有一个列表框,其中已选择了存储在数据库中的项目.现在,我想在列表框中的page_load中选择它们.我尝试了item.selected = true,但是没有用.而且我不知道该怎么做

I want to design an edit page in a web application. I have a listbox in my form which has selected items stored in my database. Now I want to have them selected on page_load in my listbox. I tried item.selected = true, but it doesn''t work. and I have no more idea how to do this

推荐答案

创建表employee(
ID int,
名称nvarchar(10),
薪水int,
开始日期日期时间,
城市nvarchar(10),
区域字符(1))
让我们假设这是我们的表.我在提供您需要使用的代码.
按照页面后面的代码创建方法.
无效的bindlist()
{
SqlCommand cmd =新的SqlCommand("select * from employee",con);
con.Open();
SqlDataReader dtr = cmd.ExecuteReader();
ListBox1.DataSource = dtr;
ListBox1.DataTextField =名称";
ListBox1.DataValueField ="ID";
ListBox1.DataBind();
con.Close();

}
并将其称为
受保护的void Page_Load(对象发送者,EventArgs e)
{
如果(!IsPostBack)
bindlist();

}
create table employee(
ID int,
name nvarchar (10),
salary int,
start_date datetime,
city nvarchar (10),
region char (1))
Let us suppose this is our table .I am giving the code that you need to use.
make a method as in the code behind of page.
void bindlist()
{
SqlCommand cmd = new SqlCommand("select * from employee", con);
con.Open();
SqlDataReader dtr = cmd.ExecuteReader();
ListBox1.DataSource = dtr;
ListBox1.DataTextField = "name";
ListBox1.DataValueField = "ID";
ListBox1.DataBind();
con.Close();

}
and call it in as
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindlist();

}


Listbox1.SelectedValue=//value from db


感谢您的答复,但这不是解决方案.让我更轻松地进行quequeion.不,我只想选择一个列表框中的所有项目,该列表框将从数据库中获取其项目.
如果ListBox在某些项目下是静态的,则此代码将选择页面加载时的所有字段:
< pre lang ="cs"> foreach(StaticListBox.Items中的ListItem索引)
{
index.Selected = true;
}</pre>
用page_load编写,但是如果列表框是动态的(属于我的),则相同的代码不起作用.我可以将ListBox绑定到数据库,但是无法使用代码选择它们.
thanks for your response, but it''s not the solution. lets make my quesyion easier. Noe I just want to select all items in a ListBox which gets its Items from a database.
if the ListBox is static with certain items, this code will select all fields on page load:
<pre lang="cs">foreach (ListItem index in StaticListBox.Items)
{
index.Selected = true;
}</pre>
which is written in page_load, but if the listbox is dynamic (which is mine), the same code does''nt work. I can bind my ListBox to a database, but I can''t select them with code.


这篇关于如何设置列表框从数据库中选择的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆