明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺!

對于.NET中WinForms里面的ListBox完成數(shù)據(jù)綁定的...

[摘要]關(guān)于.NET中WinForms里面的ListBox實現(xiàn)數(shù)據(jù)綁定的... ---------------------------------------------------------------...
關(guān)于.NET中WinForms里面的ListBox實現(xiàn)數(shù)據(jù)綁定的...

--------------------------------------------------------------------------------



在.NET中,WINDOW FORMS下面的LIST BOX控件在開發(fā)時,如果采用其本身的數(shù)據(jù)綁定,綁定完以后就不能更改ListBox的Items了.而實際開發(fā)中卻經(jīng)常會碰到要改變的情況,在這里我提供了一重方法.采用開發(fā)繼承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>
/// 必需的設(shè)計器變量。
/// </summary>
private System.ComponentModel.Container components = null;

public SysListBox()
{
// 該調(diào)用是 Windows.Forms 窗體設(shè)計器所必需的。
InitializeComponent();

// TODO: 在 InitializeComponent 調(diào)用后添加任何初始化

}

/// <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>
/// 設(shè)計器支持所需的方法 - 不要使用代碼編輯器
/// 修改此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}
而在調(diào)用這個控件時的代碼如下:

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.SelectedIn