C# 代码设置DataGrid列属性

 1 DataGridTableStyle dts = new DataGridTableStyle();
 2 dataGrid1.TableStyles.Clear();
 3 dts.MappingName = ds.Tables[0].TableName;
 4 
 5 DataGridTextBoxColumn ColID = new DataGridTextBoxColumn();
 6 ColID.HeaderText = "用户ID";
 7 ColID.MappingName = ds.Tables[0].Columns[0].ColumnName;
 8 ColID.Width = 80;
 9 dts.GridColumnStyles.Add(ColID);
10 
11 DataGridTextBoxColumn ColName = new DataGridTextBoxColumn();
12 ColName.HeaderText = "姓名";
13 ColName.Width = 100;
14 ColName.MappingName = ds.Tables[0].Columns[1].ColumnName;
15 dts.GridColumnStyles.Add(ColName);
16 
17 DataGridTextBoxColumn ColPwd = new DataGridTextBoxColumn();
18 ColPwd.HeaderText = "密码";
19 ColPwd.Width = 100;
20 ColPwd.MappingName = ds.Tables[0].Columns[2].ColumnName;
21 dts.GridColumnStyles.Add(ColPwd);
22 
23 DataGridTextBoxColumn ColLimit = new DataGridTextBoxColumn();
24 ColLimit.HeaderText = "权限";
25 ColLimit.Width = 135;
26 ColLimit.MappingName = ds.Tables[0].Columns[3].ColumnName;
27 dts.GridColumnStyles.Add(ColLimit);
28 
29 DataGridTextBoxColumn ColDept = new DataGridTextBoxColumn();
30 ColDept.HeaderText = "部门";
31 ColDept.Width = 135;
32 ColDept.MappingName = ds.Tables[0].Columns[4].ColumnName;
33 dts.GridColumnStyles.Add(ColDept);
34 
35 dataGrid1.TableStyles.Add(dts);

也可以在DataGrid的属性窗体中设置,一定要设置DataGridColumnStyle的MappingName,MappingName是和DataGrid关联的数据表中的列名;

这样设置的DataGridColumnStyle才会起作用,否则系统会自动按默认模式显示数据。

posted @ 2016-06-30 17:33  npucloud  阅读(3950)  评论(0编辑  收藏  举报