【问题标题】:DataGridView freezes when loading content and style C#加载内容和样式 C# 时 DataGridView 冻结
【发布时间】:2015-04-09 23:21:07
【问题描述】:

我的表单在选项卡控件的不同选项卡中有 6 个 dataGridViews,用户可以输入值并更改单元格背景颜色,使用保存按钮,每个 dataGridView 的值都保存到文本文件中,与背景颜色相同每个 dataGridView 中的单元格。当用户重新打开表单时,所有最后的设置(样式和值)再次加载到 6 个 dataGridViews;问题是当用户重新打开表单时,dataGridViews 冻结,我找不到解决方法。有人可以帮我吗?

我的加载数据和样式代码:

 foreach (string s in File.ReadAllLines(stylePath))
        {
            string[] items = s.Split(';');
            if (items.Length == 3)
            {
                dataGridView1.Rows[Convert.ToInt32(items[0])]
                   .Cells[Convert.ToInt32(items[1])]
                   .Style.BackColor = Color.FromName(Convert.ToString(items[2]));
            }
        }
 StreamReader sr = new StreamReader(valuePath);
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                cell.Value = sr.ReadLine();
            }
        }
        sr.Close();

以下是重新打开表单时的外观:

【问题讨论】:

  • 克里斯:我们需要查看一些代码来了解它在哪里冻结
  • 请编辑/添加您重新打开的部分,从文件中读取,更新gridViews
  • @chouaib 我注意到了更多,如果我不运行 LoadStyle void,那么 dataGridView 没有冻结。

标签: c# winforms datagridview styles freeze


【解决方案1】:

尝试:

using(StreamReader sr = new StreamReader(stylePath))
{
   string line;
   string[] items;
   int row, cell;
   Color color;

   while(!sr.EndOfStream)
   {
      line = sr.ReadLine();
      items = line.Split(';');
      if(items.Length<3) continue; //something wrong in the file

      row = Convert.ToInt32(items[0]);
      cell = Convert.ToInt32(items[1]);

      if(String.IsNullOrEmpty(item[2])) continue; // No change is needed
      color = Color.FromName(items[2]);

      dataGridView1.Rows[row].Cells[cell].Style.BackColor = color;
   }
}

【讨论】:

  • 代码成功了,颜色出现了,但是其他单元格看起来还是透明的。(我可以看穿它们) PS:对于其他单元格,我指的是没有变化的单元格。跨度>
  • @ChrisCreateBoss:我猜他们没有更改,因为他们没有设置!即使您使用文本编辑器阅读stylePath 文件,我也确信它们没有设置。对吗?
  • “设置”指的是什么
  • 例如,您将0, 0, red 0, 1, blue 作为rows[0].cells[0] = redrows[0].cells[1] = blue 的设置,但您没有可转换为其他单元格设置的文本行。这是我的问题
  • 哦,上一题你给了我一个代码,写的是列数+行数+颜色;我的输出是 0;0; 0;1; 0;2;红色; 0;3;等
猜你喜欢
  • 1970-01-01
  • 2011-08-24
  • 2017-01-25
  • 2010-10-09
  • 2019-08-06
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多