listBox数据库操作

SqlConnection con = new SqlConnection("server=(local);uid=sa;pwd=;database=zhy");
con.Open();
SqlCommand com = new SqlCommand("select * from student",con);
SqlDataReader dr = com.ExecuteReader();
this.listBox1.Items.Clear();
while (dr.Read())
{
// this.listBox1.Items.Add(dr[0].ToString());
this.listBox1.Items.Add(dr[1].ToString());//加入資料
 //   this.listBox1.Items.Add(dr[2].ToString());

 }
 dr.Close();
 con.Close();
 //this.listBox2.Items.Add(listBox1.Items.Count.ToString());

 //this.listBox2.Items.Add(this.listBox1.SelectedItem.ToString());將listBox1選種的數據加入到listBox2
 //this.listBox1.Items.Remove(this.listBox1.SelectedItem);移除listBox1中所選的項目

 

 

很少写WinForm程序第一次使用ListBox控件就遇到了比较恶心的问题。因为我不想手动绑定ListBox中的Item就使用了DataSource,但是当我进行一些添加、删除操作时就报了这个错“设置DataSource属性后无法修改项集合”。实在太恶心了,不知道设计ListBox的人是怎么想的给了DataSource属性却不能随便更改,而我要实现在一个ListBox中选中几项然后放到另一个ListBox中的功能,不能用DataSource的话太麻烦了。上博客园查了下没有找到解决办法,只能自己动手丰衣足食了。因为有人说引起这个的原因是“在winForm程序中这样绑定之后是直接和数据源DataTable相关,改动项会对DataTable造成影响”既然这样那解决方法就是如果要对Items做更改就从新弄个DataSource重新绑定,试验后效果不错。我把操作两个ListBox之间互相移动item的操作封装到一个类里,代码如下:

    说明一下,这里必须用泛型来指明所绑定的对象类型,一开始没想用泛型的,可是转移几次以后就不能按照DisplayerMember属性设置的字段来显示了比较奇怪。希望对遇到相同问题的朋友有帮助。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;

namespace BLL.App_Code
...{
//用于统一处理两个List类型控件之间互相转移Items
public static class LstCtrlMove_Mgr<T>
...{
//从一个ListBox中删除Items
public static void RemoveItems(ListBox lstBox, IEnumerable items)
...{
List<T> lst = new List<T>();
lst.AddRange((List<T>)lstBox.DataSource);
lst.RemoveAll(delegate(T item1)
...{
foreach (T item2 in items)
...{
if (item1.Equals(item2))
return true;
}
return false;
});
lstBox.DataSource = lst;
}
//向一个ListBox中添加Items
public static void AddItems(ListBox lstBox, IEnumerable items)
...{
List<T> lst = new List<T>();
if (lstBox.DataSource != null)
lst.AddRange((List<T>)lstBox.DataSource);
foreach (T item in items)
...{
lst.Add(item);
}
lstBox.DataSource = lst;
}
//将ListBox1的选定项转移到ListBox2中,并从ListBox1中去除
public static void Move(ListBox lstBox1, ListBox lstBox2)
...{
if (lstBox1.SelectedItems.Count > 0)
...{
AddItems(lstBox2, lstBox1.SelectedItems);
RemoveItems(lstBox1, lstBox1.SelectedItems);
}
}
//将整个lstBox1的项转移到ListBox2中,并清空ListBox1
public static void MoveAll(ListBox lstBox1, ListBox lstBox2)
...{
AddItems(lstBox2, (List<T>)lstBox1.DataSource);
lstBox1.DataSource = new List<T>();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值