如何定制你自己的DataGrid

王朝other·作者佚名  2006-11-24
窄屏简体版  字體: |||超大  

下面的例子显示了如何定制DataGrid,包括如何绑定一个DataTable到一个DataGrid,以及如何隐藏DataGrid中的一些列。

首先,如果你只设置DataGrid的DataSource属性是一个DataTable,那么DataGrid的TableStyle将是DefaultTableStyle,它的TableStyle.Count属性是零。所以,如果你想让你的DataGrid有个不同的table style,你必须添加你自己的table style。

下面的例子设置了一个DataGrid的data source属性,然后声明一个新的DataGridTableStyle和四个DataGridColumnStyles。这是因为在_periodData.Tables [AccountingPeriodData.AccountingPeriod_TABLE] 中有六个字段,但我只想显示四个,而且第一个必须是只读的,当然我想改变每个字段的Header Text,所以我用这个函数来实现它。注意,我们不能把HeaderText设置成一个字符串常量,我们应该从源文件中得到它。

顺便说一下,我声明了四个DataGridColumnStyle对象,但将它们更新为DataGridTextBoxColumn,这意味着你也可以将它们更新为一个DataGidBoolColumn。你当然应该知道原因啦。:-)// Initialize DataGrid when the form is opened.

private void InitializeDataGrid()

{

// set the DataGrid's datasource to a DataTable

dtgPeriods.DataSource = _periodData.Tables

[AccountingPeriodData.AccountingPeriod_TABLE];

// Create a DataGridTableStyle and set its MappingName is Accounting_TABLE

DataGridTableStyle mydtgTableStyle = new DataGridTableStyle();

mydtgTableStyle.MappingName = AccountingPeriodData.AccountingPeriod_TABLE;

// Create DataGridColumnStyles, set their properties

// Add these DataGridCollumnStyles into

the DataGridTableStyle defined above one by one

DataGridColumnStyle periodCodeStyle = new DataGridTextBoxColumn();

periodCodeStyle.MappingName = AccountingPeriodData.Period_FIELD;

periodCodeStyle.HeaderText = "會計期別";

periodCodeStyle.ReadOnly = true;

mydtgTableStyle.GridColumnStyles.Add(periodCodeStyle);

DataGridColumnStyle startDateStyle = new DataGridTextBoxColumn();

startDateStyle.MappingName = AccountingPeriodData.StartDate_FIELD;

startDateStyle.HeaderText = "期初日期";

mydtgTableStyle.GridColumnStyles.Add(startDateStyle);

DataGridColumnStyle endDateStyle = new DataGridTextBoxColumn();

endDateStyle.MappingName = AccountingPeriodData.EndDate_FIELD;

endDateStyle.HeaderText = "期末日期";

mydtgTableStyle.GridColumnStyles.Add(endDateStyle);

DataGridColumnStyle openStyle = new DataGridTextBoxColumn();

openStyle.MappingName = AccountingPeriodData.Open_FIELD;

openStyle.HeaderText = "期別開關";

mydtgTableStyle.GridColumnStyles.Add(openStyle);

// Add the DataGridTableStyle into the DataGrid's datasource.

dtgPeriods.TableStyles.Add(mydtgTableStyle);

}

关于作者:

胡晓东是GrapeCity公司国内开发部骨干。从事开发工作已超过六年。精通VB,C#,Sql Server,成功开发过多个系统,具有丰富的开发经验,也从事过Power Builder和Oracle等方面的工作。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航