【问题标题】:Datagridview updating just last rowDatagridview 仅更新最后一行
【发布时间】:2020-07-08 13:55:46
【问题描述】:
  1. 我在共享驱动器中有一个包含 xml 文件的文件夹。
  2. 该文件被合并为单个数据以进行实时监控
  3. FilesystemWatcher 监听上次修改时间并将文件加载到主数据表或合并它。
  4. datagridview rowcell 应该显示应该显示基于国家/地区的颜色。
  5. 除了 datagridview 中的颜色部分之外,我在合并文件和执行其他操作方面没有问题。
  6. 问题是下面的代码在加载文件 datagridveiw 行时会改变单元格的颜色,但是当它完成加载时,只有最后一个 datagridview 行显示彩色单元格。
  7. 最重要的是,如果用户对 datagridview 列进行排序,所有单元格都会丢失其颜色格式,包括最后一个
  8. 谁能告诉我我做错了什么或如何解决?
private void Read_Summary_XML()
{
  String[] country_array = new[] { "US", "Russia", "United Kingdom", "Cananda" };
  Color[] color_array = new Color[] { Color.FromArgb(53, 255, 51), Color.FromArgb(51, 204, 51), Color.FromArgb(255, 153, 0), Color.FromArgb(255, 153, 0) };
  List<String> direcotries_list = new List<String>(Directory.EnumerateDirectories(log_folder));
  foreach (String directory in direcotries_list)
  {
    String xml_file = Path.Combine(directory, "summary.xml");
    using (XmlReader xml_reader = new XmlNodeReader(Read_XML_File(xml_file)))
    {
      DataTable dt = new DataTable();
      dt = summary_dt.Clone();
      dt.ReadXml(xml_reader);
      summary_dt.Merge(dt);
      String country = dt.Rows[0]["country_clm"].ToString();
      DataGridViewRow row = (from dgv_row in summary_dgv.Rows.Cast<DataGridViewRow>()
                             where dgv_row.Cells["country_clm"].Value.ToString().Equals(country)
                             select dgv_row).First();
      Int32 ri = row.Index;
      row.Cells["country_clm"].Style.BackColor = color_array[Array.IndexOf(country_array, country)];

    }
 color_array = null; country_array = null;
 }
}

【问题讨论】:

  • 我看到了很多关于 DGV 的奇怪问题。所以通常我建议删除 DGV 并重新添加。这通常可以解决问题。您为 DGV 定义了多少种样式?通常有一个默认样式,当您使用一种样式更改 BackColor 时,您会更改所有行。无法解释为什么只有一行有颜色,而其他默认为无颜色。我希望所有的行都得到相同的颜色。
  • @jdweng 你知道答案吗?

标签: c# xml datatable datagridview datagridviewrow


【解决方案1】:

我已经设法找到了解决方案。在表单加载事件中添加单元格格式化事件监听器。

this.summary_dgv.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.DGV_Cell_Formatting);

private void DGV_Cell_Formatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if (summary_dgv.Columns[e.ColumnIndex].Name == "country_clm")
  {
     String[] country_array = new[] { "US", "Russia", "United Kingdom", "Cananda" };
     Color[] color_array = new Color[] { Color.FromArgb(53, 255, 51), Color.FromArgb(51, 204, 51), Color.FromArgb(255, 153, 0), Color.FromArgb(255, 153, 0) };

     summary_dgv.Rows[e.RowIndex].Cells["country_clm"].Style.BackColor = color_array[Array.IndexOf(country_array, e.Value)];
     color_array = null; country_array = null;
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多