【问题标题】:Problem with the DataTable and DataGridView objectsDataTable 和 DataGridView 对象的问题
【发布时间】:2010-09-11 19:46:29
【问题描述】:

我有以下问题

在我的应用程序中,我进行了一些计算,然后将它们放入 DataTable 对象(6 列,最新一列中的数据最重要)。要查看结果,我将它们放入 DataGridView 对象中,这是我的问题。根据最后一列中包含的数据,我想用适当的颜色标记单元格。而且我不知道我是否应该对 DataGridView 对象执行此操作,因为这是用户界面?我在哪里可以做到这一点? DataTable 对象没有样式属性?

非常感谢...

【问题讨论】:

  • 您指的是什么语言? C#?如果是 C#/.Net,请同时添加这些标签。它将帮助您更快地获得答案。

标签: c# .net datagridview datatable


【解决方案1】:

您可以使用 DataGridView 的 CellPainting 事件根据单元格的内容设置单元格的格式。

例如`

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
        {

            switch (dataGridView1.Columns[e.ColumnIndex].DataPropertyName)
            {
                case "Description":
                    {
                        break;
                    }
                case "NormalRoom":
                    {
                        break;
                    }
                case "Colour1":
                case "Colour2":
                    {
                        Color co = Color.White;
                        if (e.Value != null && e.Value != DBNull.Value)
                        {
                            co = string2Color((string)e.Value);
                        }
                        e.CellStyle.BackColor = Color.White;
                        e.CellStyle.ForeColor = Color.Black;

等等`

【讨论】:

  • Karol 的解决方案可以工作,但如果数据集很大,可能会很慢。此外,您还需要确保它在每次数据更改时运行。我的方法的优点是它是自动且高效的,因为它只需要处理屏幕上实际可见的数据。
【解决方案2】:

我做过这样的事情:

 public void setABCColor(DataGridView DGV)
    {
        for (int i = 0; i < DGV.Rows.Count; i++)
        {
            if ((string)DGV.Rows[i].Cells[6].Value == "A")
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Green;
            }
            else if ((string)DGV.Rows[i].Cells[6].Value == "B")
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Blue;
            }
            else
            {
                DGV.Rows[i].Cells[6].Style.BackColor = Color.Red;
            }
        }
    }

这可以接受吗?这不是改变MVC设计模式的假设吗?

【讨论】:

    【解决方案3】:

    我建议将逻辑放在 datagridview 的单元格格式化事件中。 如果您的数据根据​​网格中的某些计算动态变化,这些也将反映变化 像

    void myDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
                if (e.Value.ToString() == "A" )
                    e.CellStyle.BackColor = Color.Red;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-26
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多