在MVC 中绑定模型的视图,很多时候都会用到下拉框,所以在此记录一下根据DataTable中的数据给下拉框填充数据的方法
1 /// <summary> 2 /// 将 DataTable 转成下拉框的填充数据List<SelectListItem>类型 3 /// </summary> 4 /// <param name="dt">数据DataTable</param> 5 /// <param name="keyColumnName">展示文本列</param> 6 /// <param name="valueColumnName">选中值列</param> 7 /// <param name="has请选择">是否使用请选择</param> 8 /// <param name="has请选择Text">请选择的文本 默认为 =请选择=</param> 9 /// <param name="defaultValue">默认下拉框选中的值</param> 10 /// <returns></returns> 11 public static List<SelectListItem> bindValues(DataTable dt, string keyColumnName, string valueColumnName, bool has请选择 = false, string has请选择Text = "", string defaultValue = "") 12 { 13 List<SelectListItem> list = new List<SelectListItem>(); 14 if (has请选择) 15 { 16 SelectListItem item = new SelectListItem() { Text = has请选择Text == "" ? “=请选择=” : has请选择Text, Value = "" }; 17 list.Add(item); 18 } 19 20 21 if (dt.Rows.Count == 0) 22 return list; 23 List<Tuple<string, string>> valueList = DataTableToList(dt, keyColumnName, valueColumnName); 24 foreach (var item in valueList) 25 { 26 if (defaultValue != “” && defaultValue.Contains(item.Item1)) 27 list.Add(new SelectListItem() { Text = item.Item2, Value = item.Item1, Selected = true }); 28 else 29 list.Add(new SelectListItem() { Text = item.Item2, Value = item.Item1, Selected = false }); 30 } 31 return list; 32 }
这个方法是将指定多列数据的DataTable的某一列为展示文本,某一列为选中值,然后根据元组Tuple为List的项来存放。元组是C#7.0中新出来的,有兴趣的可以了解一下。
1 /// <summary> 2 /// 将DataTable转成List 3 /// </summary> 4 /// <param name="table">要转的DataTable</param> 5 /// <param name="keyColumnName">指定展示文本列</param> 6 /// <param name="valueColumnName">指定选中值列</param> 7 /// <returns></returns> 8 public static List<Tuple<string, string>> DataTableToList(DataTable table, string keyColumnName, string valueColumnName) 9 { 10 List<Tuple<string, string>> list = new List<Tuple<string, string>>(); 11 if (table.Rows.Count == 0) 12 return null; 13 for (int i = 0; i < table.Rows.Count; i++) 14 { 15 list.Add(new Tuple<string, string>(table.Rows[i][keyColumnName].ToString(), table.Rows[i][valueColumnName].ToString())); 16 } 17 return list; 18 }
原文地址:https://www.cnblogs.com/yanwu/p/11103297.html
时间: 2024-10-13 23:26:58