[英]Add new column programmatically to DataGridView (DataGridview Filled with DataTable)
[英]Programmatically add new column to DataGridView
我有一个绑定到DataTable的DataGridView。 DataTable是从数据库查询填充的。 该表包含一个名为BestBefore的列。 BestBefore是格式化为字符串的日期(SQLite没有日期类型)。
我想以编程方式向DataGridView添加一个名为Status的新列。 如果BestBefore小于当前日期,则Status值应设置为OK,否则Status值应设置为NOT OK。
我是Winforms的新手,所以我们非常感谢一些示例代码。
更新:
我认为DataColumn.Expression可以进行简单的计算,例如将列的整数值乘以另一个值,但是如何做我需要做的事情呢? 也就是说,计算nowBefore列中now和date(字符串格式化)之间的差异,以确定为新状态列提供的值。 示例代码将不胜感激。
把事情简单化
dataGridView1.Columns.Add("newColumnName", "Column Name in Text");
添加行
dataGridView1.Rows.Add("Value for column#1"); // [,"column 2",...]
将新列添加到DataTable
并使用列Expression
属性来设置Status表达式。
在这里你可以找到很好的例子: DataColumn.Expression
属性
ADO.NET中的DataTable和DataColumn表达式 - 计算列
UPDATE
代码示例:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));
dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));
demoGridView.DataSource = dt;
更新#2
dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
这是一个示例方法,它以编程方式向网格视图添加两个额外的列:
private void AddColumnsProgrammatically()
{
// I created these columns at function scope but if you want to access
// easily from other parts of your class, just move them to class scope.
// E.g. Declare them outside of the function...
var col3 = new DataGridViewTextBoxColumn();
var col4 = new DataGridViewCheckBoxColumn();
col3.HeaderText = "Column3";
col3.Name = "Column3";
col4.HeaderText = "Column4";
col4.Name = "Column4";
dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
}
了解如何执行此类过程的一种好方法是创建表单,添加网格视图控件并添加一些列。 (此过程实际上适用于任何类型的表单控件。所有实例化和初始化都在Designer中进行。)然后检查表单的Designer.cs文件以查看构造是如何进行的。 (Visual Studio以编程方式执行所有操作,但将其隐藏在“表单设计器”中。)
对于此示例,我为名为Column1和Column2的视图创建了两列,然后在Form1.Designer.cs中搜索Column1以查看它被引用的所有位置。 以下信息是我收集,复制和修改以动态创建两列的信息:
// Note that this info scattered throughout the designer but can easily collected.
System.Windows.Forms.DataGridViewTextBoxColumn Column1;
System.Windows.Forms.DataGridViewCheckBoxColumn Column2;
this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Column1,
this.Column2});
this.Column1.HeaderText = "Column1";
this.Column1.Name = "Column1";
this.Column2.HeaderText = "Column2";
this.Column2.Name = "Column2";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.