關於.NET中WinForms裡面的ListBox實現資料繫結的...
來源:互聯網
上載者:User
資料 關於.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);