gpt4 book ai didi

c# - 根据值更改 DataGridView 列的颜色

转载 作者:行者123 更新时间:2023-12-04 13:08:11 24 4
gpt4 key购买 nike

我正在尝试根据其值更改 DataGridView 中列的颜色。这是我的代码。但是,我在 if 语句中出错。

如果 Column 的值小于零,我想将其背景颜色更改为 Color.Red。

private void DataColor()
{
foreach (DataGridViewColumn col in MyDataGrid.Columns)
if (Convert.ToInt32(col[5].Value) < 0)
{
MessageBox.Show("Test");

}
}

我需要的输出:

Output

最佳答案

看看以下内容是否适合您使用 .NET Framework 4.8 完成。将 DataGridView 添加到新窗体,添加下面的代码,将窗体名称更改为您的窗体名称。

Full code

enter image description here

using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace DataGridViewCellFormatting1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Shown += OnShown;
}

private void OnShown(object sender, EventArgs e)
{
dataGridView1.DataSource = MockedDataTable.Table();
dataGridView1.CellFormatting += DataGridView1OnCellFormatting;
}

private const string _amountColumnName = "Amount";
private void DataGridView1OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (!dataGridView1.Columns[e.ColumnIndex].Name.Equals(_amountColumnName)) return;
if (e.Value == null || !int.TryParse(e.Value.ToString(), out var amount)) return;

dataGridView1.Rows[e.RowIndex].Cells[_amountColumnName].Style.BackColor = amount >0 ?
Color.Empty :
Color.Red;
}
}

public class MockedDataTable
{
public static DataTable Table()
{
var dt = new DataTable();

dt.Columns.Add(new DataColumn()
{
ColumnName = "id",
DataType = typeof(int),
AutoIncrement = true,
AutoIncrementSeed = 1
});

dt.Columns.Add(new DataColumn() { ColumnName = "Amount", DataType = typeof(int) });

dt.Rows.Add(null, 200);
dt.Rows.Add(null, 1000);
dt.Rows.Add(null, -3200);
dt.Rows.Add(null, -300);
dt.Rows.Add(null, 500);


return dt;
}
}
}

关于c# - 根据值更改 DataGridView 列的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68393146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com