日期:2014-05-20  浏览次数:20750 次

如何获得DataGridViewCurrentCell中内容的前景颜色?
运行环境:Windows XP(SP3)+vs.net2005+Crystal Reports XI

代码如何:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace test
{
  public partial class Form5 : Form
  {
  public Form5()
  {
  InitializeComponent();
  }

  private void Form5_Load(object sender, EventArgs e)
  {
  DataTable dt = new DataTable();
  DataColumn dc = new DataColumn("id", typeof(String));
  dt.Columns.Add(dc);
  dc = new DataColumn("name", typeof(String));
  dt.Columns.Add(dc);
  for (int i = 0; i <= 20; i++)
  dt.Rows.Add(i, "row" + i);
  this.dataGridView1.DataSource = dt;
  }

  private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
  {
  if (e.RowIndex == -1 || e.ColumnIndex == -1)
  return;
  if (e.RowIndex % 2 == 0 && e.ColumnIndex == 1)
  e.CellStyle.ForeColor = Color.Blue;
  }

  private void button1_Click(object sender, EventArgs e)
  {
  MessageBox.Show("CurrentCell.InheritedStyle.ForeColor:" + this.dataGridView1.CurrentCell.InheritedStyle.ForeColor.Name
  + "\r\n\r\nCurrentCell.OwningColumn.InheritedStyle.ForeColor:" + this.dataGridView1.CurrentCell.OwningColumn.InheritedStyle.ForeColor.Name
  + "\r\n\r\nCurrentCell.OwningColumn.DefaultCellStyle.ForeColor:" + this.dataGridView1.CurrentCell.OwningColumn.DefaultCellStyle.ForeColor.Name);
  }
  }
}
说明:DataGridView所有属性均为默认值。

当我选择有改变颜色的DataGridViewCell后,点击按钮,获得的颜色却没有我设置的颜色Blue


------解决方案--------------------
改成:DataGridViewCell.Style
------解决方案--------------------
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
{
DataGridView dgv = (DataGridView)sender;
dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Red;
dgv[e.ColumnIndex, e.RowIndex].Style.SelectionBackColor = Color.Red;
Color col=dgv.CurrentCell.Style.ForeColor;
}


}