關於.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);


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.