获取dataGridView C#中所有单元格的BackColor



我想获得所有单元格的BackColor并将其写入文本文件,因此输出为:黄绿色橙色钢蓝

这就是我尝试过的:

 void GetColors()
    {
        string path = Application.StartupPath + @"/test.txt";
        StreamWriter sw = new StreamWriter(path);
        int n = 0;
        DataGridViewColumn column = dataGridView1.Columns[n++];
        DataGridViewCell cell = new DataGridViewTextBoxCell();
        sw.WriteLine(cell.Style.BackColor);
        column.CellTemplate = cell;
        sw.Close();
    }

我试过cell.Style.BackColor.ToString();.ToArgb();使用ToString();我在输出中得到Color {Empty},使用ToArgb得到0

有人能帮帮我吗?提前感谢。。。

创建新的DataGridViewTextBoxCell对象时,没有引用现有单元格。

尝试枚举现有单元格:

foreach (DataGridViewRow row in dataGridView1.Rows) {
  foreach (DataGridViewCell cell in row.Cells) {
    sw.WriteLine(cell.Style.BackColor.ToKnownColor().ToString());
  }
}

要保存和读取网格的配色方案,您可以将行和列信息保存到字符串中:

foreach (DataGridViewRow row in dataGridView1.Rows) {
  foreach (DataGridViewCell cell in row.Cells) {
    sw.WriteLine(string.Join(";", cell.RowIndex.ToString(),
                                  cell.ColumnIndex.ToString(),
                                  GetColorName(cell.Style.BackColor)));
  }
}

GetColorName函数来自于如何在C#中具有RGB值的情况下获得颜色的名称?

要用文件中的颜色更新网格,您需要解析信息:

foreach (string s in File.ReadAllLines(@"yourfile")) {
  string[] items = s.Split(';');
  if (items.Length == 3) {
    dgv.Rows[Convert.ToInt32(items[0])]
       .Cells[Convert.ToInt32(items[1])]
       .Style.BackColor = Color.FromName(Convert.ToString(items[2]));
  }
}

为简洁起见,省略了任何错误检查。显然,文件中的行数和列数必须与datagridview控件显示的内容相匹配。

最新更新