我有一个绑定到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小于当前日期,则应将状态值设置为确定,否则应将状态值设置为不正确。
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
DataTable和DataColumn 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;UPDATE#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添加新列
发布评论