淺析C# 綁定ComBobox控件的解決方法
一般的C# 綁定,都是將ID進(jìn)行遞歸,然后再幫頂。這里將解決普通綁定中會出現(xiàn)的問題。希望對大家有所幫助。
在C/S模式下,在這樣一種情況下:
ID |
NAME |
ParentID |
1 | aa | 0 |
2 | bb | 1 |
3 | cc | 2 |
從以上圖標(biāo)中可看出關(guān)系:ID:1是父節(jié)點,ID:2是ID:1的子節(jié)點,而ID:3又是ID:2的子節(jié)點。這種關(guān)系其實并不復(fù)雜,但是你要通過一個Combobox來檢索出ID:1節(jié)點下的所有節(jié)點,就必須使用遞歸了。因此,問題也就出現(xiàn)了,用普遍的方式來C# 綁定,會使界面上數(shù)量顯示成[ Control:name ] ,具體的筆者不再重復(fù),如果你看到這篇文章,那么你應(yīng)該會明白我的意思。好,下面來看解決方案吧!
寫一個ListItem類:
- public class ListItem
- {
- private string id = string.Empty;
- private string name = string.Empty;
- public ListItem(string sid, string sname)
- {
- id = sid;
- name = sname;
- }
- public override string ToString()
- {
- return this.name;
- }
- public string ID
- {
- get
- {
- return this.id;
- }
- set
- {
- this.id = value;
- }
- }
- public string Name
- {
- get
- {
- return this.name;
- }
- set
- {
- this.name = value;
- }
- }
- }
C# 綁定方法:
- //定義一個方法,傳兩個參數(shù);
- // 注意:參數(shù)得看你的具體需要,筆下這個方法僅作參考;
- void init(ComboBox cb, int parentId)
- {
- string commandText = String.Format("Select * from tb_SystemCategory where parentID= {0}",parentId);
- DataSet ds = globalBLL.GetList(commandText);
- if (ds != null)
- {
- foreach (DataRow dr in ds.Tables[0].Rows)
- {
- Global.ListItem item = new LMInvoicingCS.Global.ListItem(dr["id"].ToString(),dr["name"].ToString());
- cb.Items.Add(item);
- init(cb, int.Parse(dr["id"].ToString()));
- }
- ds = null;
- }
- }
基本上到這里就可以了,以下是我在“添加/修改”時作的一些設(shè)置。
; 添加的時候,綁定完控件,顯示的應(yīng)該是第一條數(shù)據(jù),因此:
cboCategory.SelectedItem = cboCategory.Items[0];
;修改一條數(shù)據(jù),綁定完控件,顯示給客戶的綁定項應(yīng)該是該編輯項的category,因此:
- // 定義一個方法;
- // 這個方法的效率不高,屬于老土型,如果有哪位朋友有更好的方案,歡迎交流,謝謝!
- private int com(string value)
- {
- int index = -1;
- for (int i = 0; i < rca.cboCategory.Items.Count; i++)
- {
- if (((ListItem)rca.cboCategory.Items[i]).ID == value)
- {
- index = i;
- }
- }
- return index;
- }
- // 調(diào)用方法
- int indext = com(this.treeViewer.SelectedNode.Tag.ToString());
- cboCategory.SelectedItem = cboCategory.Items[indext];
【編輯推薦】