一般的C# 绑定,都是将ID进行递归,然后再帮顶。这里将解决普通绑定中会出现的问题。希望对大家有所帮助。
在C/S模式下,在这样一种情况下:
ID |
NAME |
ParentID |
1 | aa | 0 |
2 | bb | 1 |
3 | cc | 2 |
从以上图标中可看出关系:ID:1是父节点,ID:2是ID:1的子节点,而ID:3又是ID:2的子节点。这种关系其实并不复杂,但是你要通过一个Combobox来检索出ID:1节点下的所有节点,就必须使用递归了。因此,问题也就出现了,用普遍的方式来C# 绑定,会使界面上数量显示成[ Control:name ] ,具体的笔者不再重复,如果你看到这篇文章,那么你应该会明白我的意思。好,下面来看解决方案吧!
写一个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;
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
C# 绑定方法:
//定义一个方法,传两个参数;
// 注意:参数得看你的具体需要,笔下这个方法仅作参考;
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;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
基本上到这里就可以了,以下是我在“添加/修改”时作的一些设置。
; 添加的时候,绑定完控件,显示的应该是第一条数据,因此:
cboCategory.SelectedItem = cboCategory.Items[0];
;修改一条数据,绑定完控件,显示给客户的绑定项应该是该编辑项的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;
}
// 调用方法
int indext = com(this.treeViewer.SelectedNode.Tag.ToString());
cboCategory.SelectedItem = cboCategory.Items[indext];
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
【编辑推荐】