在项目中用到了DevExpress的ASPxGridview控件,每每去配置它的时候,总感觉很是啰嗦,于是想到了用代码自动配置。
于是有了这样的代码:
foreach (ZiyuWeb.Entity.Sys_UIConfig item in sConfigs) { switch (item.ControlName) { case "ASPxDropDown_ASPxCheckListBox": { DevExpress.Web.ASPxGridView.GridViewDataDropDownEditColumn col = new GridViewDataDropDownEditColumn();//创建一个表格列; col.FieldName = item.FieldName;//表格列绑定的数据源字段名称 col.Caption = item.FieldDescribe;//字段显示标题 col.Name = "col_" + item.FieldName;//列名称 col.VisibleIndex = item.OrderByID;//显示顺序 col.Width = item.Width;//显示宽度 col.Visible = item.UserIsVisible;//是否可见 col.ReadOnly = item.UserReadOnly;//是否只读 // col.EditItemTemplate = new ZiyuWeb.ASPxCheckListBox_DropDownTemplate("", item.QueryStr, col.Name);//创建该字段的编辑模板,如果是标准的DevExpress.Web.ASPxEditor则无需创建编辑模板了。但若是DropDown或者自己写的控件,就必须自行创建了。 mygridview.Columns.Add(col);//添加到View; break; } …… } }
有了上面代码创建的表格,则ASPxGridview控件只需要设置一下配置文件名称和数据源,便可以以一行代码来完美展现了。
ZiyuWeb.WebFunc.ZiyuDevHelper.configGridView(ASPxGridView1, "Sys_UIConfig", true, null);
创建EditItemTemplate。
class MyTemplate_AspxCheckBoxList : ITemplate { int _iwidth = 80; public int Iwidth { get { return _iwidth; } set { _iwidth = value; } } ZiyuWeb.Entity.Sys_UIConfig uiconfig; public MyTemplate_AspxCheckBoxList(ZiyuWeb.Entity.Sys_UIConfig myuiconfig) { uiconfig = myuiconfig; Iwidth = uiconfig.Width; } public void InstantiateIn(Control container) { DevExpress.Web.ASPxEditors.ASPxCheckBoxList alistbox = new ASPxCheckBoxList(); alistbox.TextField = uiconfig.FieldName; alistbox.ValueField = uiconfig.FieldName; if (uiconfig.QueryStr != null) { if (uiconfig.QueryStr.Length > 0) { if (uiconfig.QueryStr.IndexOf("select") >= 0) { System.Collections.ArrayList alist = MyHelper4Web.MyStringHelper.getTableNamefromSql(uiconfig.QueryStr); XCode.DataAccessLayer.DAL mydal = XCode.DataAccessLayer.DAL.Create("common"); System.Data.DataTable dt = mydal.Select(uiconfig.QueryStr, alist[0].ToString()).Tables[0]; if (dt.Columns.Count == 1) { for (int i = 0; i < dt.Rows.Count; i++) { alistbox.Items.Add(dt.Rows[i][0].ToString()); } } } else { System.Collections.ArrayList alist = MyHelper4Web.MyConvertHelper.ConvertStringToArrayList(uiconfig.QueryStr, ";"); for (int i = 0; i < alist.Count; i++) { alistbox.Items.Add(alist[i].ToString()); } } } } alistbox.ID = "myCon_" + uiconfig.FieldName; alistbox.ClientInstanceName = "myCon_" + uiconfig.FieldName; alistbox.RepeatColumns = 3; alistbox.TextWrap = false; alistbox.RepeatDirection = RepeatDirection.Horizontal; alistbox.RepeatLayout = RepeatLayout.Flow; string rowValue = (container as GridViewEditItemTemplateContainer).Text; string[] rowValueItems = rowValue.Split(';'); List<string> rowValueItemsAsList = new List<string>(); rowValueItemsAsList.AddRange(rowValueItems); foreach (ListEditItem item in alistbox.Items) if (rowValueItemsAsList.Contains(item.Value.ToString())) item.Selected = true; container.Controls.Add(alistbox); } }