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

80酷酷网    80kuku.com

  数据关于.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
{
/// <summary>
/// SysListBox 的摘要说明。
/// </summary>
public class SysListBox : System.Windows.Forms.ListBox
{
private SortedList _sl=new SortedList();
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.Container components = null;

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

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

}

/// <summary>
/// 清理所有正在使用的资源。
/// </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<this.DataValues.Count;i++)
{
this.Items.Add(this.DataValues.GetByIndex(i).ToString());
}
this.EndUpdate();
}
}
#region Component Designer generated code
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器
/// 修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}
而在调用这个控件时的代码如下:

string mkey=this.listCanSel.DataValues.GetKey(this.listCanSel.SelectedIndex).ToString();
string mtext=this.listCanSel.DataValues.GetByIndex(this.listCanSel.SelectedIndex).ToString();
this.listSel.AddItem(mkey,mtext);
this.listCanSel.RemoveItem(this.listCanSel.SelectedIndex);

this.listSel.Items.Add(mtext);
this.listCanSel.Items.RemoveAt(this.listCanSel.SelectedIndex);

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: