加载内容和样式C#时DataGridView冻结

时间:2015-02-10 02:18:16

标签: c# winforms datagridview styles freeze

我的表单在选项卡Control的不同选项卡中有6个dataGridViews,用户可以输入值并更改单元格backcolor,使用保存按钮,每个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();

以下是重新打开表单时的外观: enter image description here

1 个答案:

答案 0 :(得分: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;
   }
}