gpt4 book ai didi

c# - 以编程方式更改datagridview中的颜色单元格

转载 作者:太空宇宙 更新时间:2023-11-03 13:12:47 24 4
gpt4 key购买 nike

我尝试改变 DataGridView 中单元格的颜色。

我对 datagridview 有点陌生,看过这里发布的许多问题,但似乎没有一个对我有用。

我的最终迭代(仍然不起作用)是:

DataGridView1.AutoGenerateColumns = true;
DataGridView1.AutoSize = true;
DataGridView1.DataSource = DT;
int rowIndex = 0;
int cellIndex = 0;
Color c = Color.Gray;
foreach(var row in DataGridView1.Rows.Cast<DataGridViewRow>().ToList())//.ForEach(row =>
{
var cells = row.Cells;
if (cells.Count > 0) {
cellIndex = 0;
foreach (DataGridViewCell cell in cells)
{
DataGridView1.Rows[rowIndex].Cells[cellIndex].Style.BackColor = c;
//cell.Style.BackColor = c;
cellIndex++;

}
if (cells[0].Value!= null)
if ((cells[0].Value as string ).Contains("==="))/*end of section*/
{
c = (c == Color.Gray) ? Color.Transparent : Color.Gray;/*change color at end of section*/
}
}
rowIndex++;
}
rowIndex = 0;

我的代码可能有什么问题?是否需要在 True\False 上设置任何参数才能更改颜色?

编辑我做什么:我想打开只有 DataGridView 的新表单,所以数据和所有其他用途都与上下文菜单(MouseButtons.Right)

更多代码

public partial class ResultsDiffForm : Form 
{
public ResultsDiffForm(DataTable DT)//consatructor
{
InitializeComponent();
/*Old code goes here ... */
}
}

应该更清楚我在做什么。

最佳答案

您没有发布调用此代码的位置,但是当您尝试在窗体的构造函数中设置单元格属性时,WinForms 中的 DataGridView 控件很挑剔。

尝试改用 OnLoad 覆盖:

protected override void OnLoad(EventArgs e) {
base.OnLoad(e);

// your DataGridView code here...
}

关于c# - 以编程方式更改datagridview中的颜色单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27723890/

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