如何根据条件更改DataGridView列值 [英] How to change DataGridView column value based on condition

查看:264
本文介绍了如何根据条件更改DataGridView列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以根据条件更改列值或单元格值?

Is it possible to change the column value or cell value based on the Condition?

考虑我在 DataGridView (即)找到最大的两个数字

Consider I am having 3 columns in a DataGridView (i.e) to find the greatest of two number

DataGridView 从SQL Server获取。

The input from DataGridView is got from SQL Server.

第一个Datagridview列是A,第二个是B,第三列是发现A是否大于B。如果条件满足,则应在第3列中显示文本TRUEFALSE

First Datagridview column is A and second one is B and 3rd column is to find whether A is bigger than B or not. if the condition satisfies it should display the text "TRUE" or else "FALSE" in 3rd Column.

推荐答案

我已经回答了类似的问题更改DataGridView的单元格

I have answered a similar question here Changing Cell Values of DataGridView

您可以使用 DataGridView.CellFormatting 事件。在您的情况下,您需要为每个行检索其他值的单元格当第三个单元格需要格式化时。

You can use the DataGridView.CellFormatting event. In your case you need to retrieve, for each Rows, the value of others Cells when the third Cell needs to be formatted.

下面的示例代码假定:


  • 中的 int DataGridView :您需要进行适当的转换。

  • no Null DbNull 值:如果需要,您需要检查空值。

  • values are int in DataGridView: you need to do the appropriate conversion.
  • no Null, DbNull Values: you need to check for null values if required.
void dgv_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 2) {
        if (Convert.ToInt32(this.dgv.Rows[e.RowIndex].Cells[0].Value) > Convert.ToInt32(this.dgv.Rows[e.RowIndex].Cells[1].Value)) {
            e.Value = "TRUE";
        } else {
            e.Value = "FALSE";
        }
        e.FormattingApplied = true;
    }
}

这篇关于如何根据条件更改DataGridView列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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