以编程方式向DataGridView添加新列

编程入门 行业动态 更新时间:2024-10-26 14:39:57
本文介绍了以编程方式向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小于当前日期,则应将状态值设置为确定,否则应将状态值设置为不正确。

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添加新列

本文发布于:2023-11-12 18:43:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方式   DataGridView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!