Winform为Combobox添加树形数据
先看效果图:
实现代码:
/// <summary>
/// 绑定ComboBox
/// </summary>
/// <param name="cmb">ComboBox控件</param>
/// <param name="cityNo">根地区编号</param>
/// <param name="pre">传入string.Empty</param>
/// <param name="level">传入0</param>
public static void BindComboBoxTree(ComboBox cmb, string cityNo, string pre, int level)
{
IList<AreaTInfo> areaList = CacheData.Instince.GetCache("AreaList") as IList<AreaTInfo>;
if (areaList == null)
{
IReprotService _porxy = ServiceProxyFactory.Create<IReprotService>("ReportService");
areaList = _porxy.GetAreaInfo().ToList<AreaTInfo>();
CacheData.Instince.SetCache("AreaList", areaList);
}
List<AreaTInfo> list = new List<AreaTInfo>();
foreach (AreaTInfo ai in areaList)
{
if (ai.F_AreaSN == cityNo)
{
list.Add(ai);
}
}
string temPre = string.Empty;
if (level > 0) //判断是否是跟节点
{
temPre = pre + "|--";
}
foreach (AreaTInfo item in list) //
{
item.AreaName = temPre + item.AreaName;
cmb.Items.Add(item);
level++;
BindComboBoxTree(cmb, item.AreaSN, temPre, level); //递归实现
}
cmb.ValueMember = "AreaSN"; //实体类中显示的值
cmb.DisplayMember = "AreaName"; //对应实体类中的值
cmb.SelectedIndex = 0;
}
/// 绑定ComboBox
/// </summary>
/// <param name="cmb">ComboBox控件</param>
/// <param name="cityNo">根地区编号</param>
/// <param name="pre">传入string.Empty</param>
/// <param name="level">传入0</param>
public static void BindComboBoxTree(ComboBox cmb, string cityNo, string pre, int level)
{
IList<AreaTInfo> areaList = CacheData.Instince.GetCache("AreaList") as IList<AreaTInfo>;
if (areaList == null)
{
IReprotService _porxy = ServiceProxyFactory.Create<IReprotService>("ReportService");
areaList = _porxy.GetAreaInfo().ToList<AreaTInfo>();
CacheData.Instince.SetCache("AreaList", areaList);
}
List<AreaTInfo> list = new List<AreaTInfo>();
foreach (AreaTInfo ai in areaList)
{
if (ai.F_AreaSN == cityNo)
{
list.Add(ai);
}
}
string temPre = string.Empty;
if (level > 0) //判断是否是跟节点
{
temPre = pre + "|--";
}
foreach (AreaTInfo item in list) //
{
item.AreaName = temPre + item.AreaName;
cmb.Items.Add(item);
level++;
BindComboBoxTree(cmb, item.AreaSN, temPre, level); //递归实现
}
cmb.ValueMember = "AreaSN"; //实体类中显示的值
cmb.DisplayMember = "AreaName"; //对应实体类中的值
cmb.SelectedIndex = 0;
}
读出combobox的值时
AreaTInfo temparea = this.com_Area.SelectedItem asAreaTInfo; //AreaTInfo为实体类 Com_Area为combobox控件
if (temparea != null)
{
StrAreaSN = temparea.AreaSN; //读取实体类中的AreaSN
}
else
{
StrAreaSN = "";
}
if (temparea != null)
{
StrAreaSN = temparea.AreaSN; //读取实体类中的AreaSN
}
else
{
StrAreaSN = "";
}