[英]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.