关于.NET中WinForms里面的ListBox实现数据绑定的解决方法

在.NET中,WINDOW FORMS下面的LIST BOX控件在开发时,如果采用其本身的数据绑定,绑定完以后就不能更改ListBox的Items了.而实际开发中却经常会碰到要改变的情况,在这里我提供了一重方法.采用开发继承ListBox控件的自定义控件.然后在里面提供两个SortedList类的属性,一个可以存放ID,一个存放TEXT,这样就解决了上面说的问题!!

控件的代码如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;

namespace FlowManage
{
///

1<summary>   
2/// SysListBox 的摘要说明。   
3/// </summary>

public class SysListBox : System.Windows.Forms.ListBox
{
private SortedList _sl=new SortedList();
///

1<summary>   
2/// 必需的设计器变量。   
3/// </summary>

private System.ComponentModel.Container components = null;

public SysListBox()
{
// 该调用是 Windows.Forms 窗体设计器所必需的。
InitializeComponent();

// TODO: 在 InitializeComponent 调用后添加任何初始化

}

///

1<summary>   
2/// 清理所有正在使用的资源。   
3/// </summary>

protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

public SortedList DataValues
{
get
{
return _sl;
}
set
{
_sl=value;
}
}
public void AddItem(object key,object text)
{
if(this.DataValues==null)
{
this.DataValues=new SortedList();
}
this.DataValues.Add(key,text);
}
public void RemoveItem(int index)
{
this.DataValues.RemoveAt(index);
}
public void RemoveItem()
{
this.DataValues.Clear();
}
public void BoundList()
{
this.Items.Clear();
if(this.DataValues!=null)
{
this.BeginUpdate();
for(int i=0;i

 1<this.datavalues.count;i++) #region="" <summary="" code="" component="" designer="" generated="" this.endupdate();="" this.items.add(this.datavalues.getbyindex(i).tostring());="" {="" }="">   
 2/// 设计器支持所需的方法 - 不要使用代码编辑器   
 3/// 修改此方法的内容。   
 4///    
 5private void InitializeComponent()   
 6{   
 7components = new System.ComponentModel.Container();   
 8}   
 9#endregion   
10}   
11}   
12而在调用这个控件时的代码如下: 
13
14string mkey=this.listCanSel.DataValues.GetKey(this.listCanSel.SelectedIndex).ToString();   
15string mtext=this.listCanSel.DataValues.GetByIndex(this.listCanSel.SelectedIndex).ToString();   
16this.listSel.AddItem(mkey,mtext);   
17this.listCanSel.RemoveItem(this.listCanSel.SelectedIndex); 
18
19this.listSel.Items.Add(mtext);   
20this.listCanSel.Items.RemoveAt(this.listCanSel.SelectedIndex); 
21
22以上只是个人使用中的拙见,欢迎大家提出更好的解决办法!</this.datavalues.count;i++)>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus