以编程方式将新列添加到 DataGridView [英] Programmatically add new column to DataGridView

查看:39
本文介绍了以编程方式将新列添加到 DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到 DataTable 的 DataGridView.DataTable 是根据数据库查询填充的.该表包含一个名为 BestBefore 的列.BestBefore 是格式化为字符串的日期(SQLite 没有日期类型).

I have a DataGridView bound to a DataTable. The DataTable is populated from a database query. The table contains a column named BestBefore. BestBefore is a date formatted as a string (SQLite doesn't have date types).

我想以编程方式向 DataGridView 添加一个名为 Status 的新列.如果 BestBefore 小于当前日期,则应将 Status 值设置为 OK,否则应将 Status 值设置为 NOT OK.

I would like to programmatically add a new column to the DataGridView called Status. If BestBefore is less than the current date, Status value should be set to OK, otherwise Status value should be set to NOT OK.

我对 Winforms 非常陌生,因此非常感谢一些示例代码.

I'm very new to Winforms, so some example code would be greatly appreciated.

更新:

我认为 DataColumn.Expression 可以进行简单的计算,例如将列的整数值乘以另一个值,但是我需要做什么呢?也就是说,计算现在和 BestBefore 列中的日期(字符串格式)之间的差异,以确定为新状态列提供什么值.示例代码将不胜感激.

I think DataColumn.Expression is okay for doing simple calculations such multiplying a column's integer value by another value, but what about doing what I need to do? That is, calculate the difference between now and the date (string formatted) in the BestBefore column to determine what value to give the new status column. Example code would be appreciated.

推荐答案

将新列添加到 DataTable 并使用列 Expression 属性设置您的状态表达式.

Add new column to DataTable and use column Expression property to set your Status expression.

在这里你可以找到很好的例子:DataColumn.Expression 属性

Here you can find good example: DataColumn.Expression Property

ADO.NET 中的数据表和数据列表达式 - 计算列

更新

代码示例:

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"));

这篇关于以编程方式将新列添加到 DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆