[英]For a Windows Forms Application using `DataGridView`, how can I check a value in my DataSource and change the color of a separate cell?
我知道非常具体的问题。 我不确定如何最好地表达这一点。 当前,我的cell_formatting
方法将根据其值更改单元格的颜色:
dataGridView.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.cell_formatting);
....
public void cell_formatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (dataGridView.Columns[e.ColumnIndex].Name.Equals("LocCode"))
{
if (e.Value.ToString() == "OK")
{
e.CellStyle.BackColor = Color.Red;
}
}
}
我实际上需要做的是检查与我要更改颜色的列索引不同的列索引。 有一种列color
将决定LocCode
单元格将更改为哪种颜色。
我想有一种方法可以捕获在cell_formatting()
内的dataGridView.DataSource
哪个项目,但是我不知道如何访问它。
我建议您使用DataTable来获取颜色值。 这是一个简单的例子。
我做了一个表,并在其中添加了3条记录。
在form_load中,将数据加载到DataGridView中,
DataTable dt;
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=serverName;Database=db;Trusted_Connection=True");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from TestTable", conn);
dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
dataGridView1.DataSource = dt;
}
然后,我们来到了cell_formatting事件,
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("TestName")) // LocCode
{
if (e.Value != null && e.Value.ToString() != "") // Check for extra line
{
string a = dt.Rows[e.RowIndex]["Color"].ToString(); //current row's Color column value.
e.CellStyle.BackColor = Color.FromName(a); // color as backcolor
}
}
}
输出;
希望有帮助,
我想有一种方法可以捕获在cell_formatting()内的dataGridView.DataSource中的哪个项目,但是我不知道如何访问它。
当然可以。
首先,使用DataGridViewCellFormattingEventArgs.RowIndex
属性获取要格式化的行的索引。 然后使用索引获取对应的DataRow
对象,最后使用DataGridViewRow.DataBoundItem
属性获取对应的数据源对象,并将其转换为适当的类型:
var item = dataGridView.Rows[e.RowIndex].DataBoundItem as YourDataSourceObjectType;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.