[英]Can I change my datagridview cell font style based on a condition?
我有一個有界的datagridview和一列是從數據庫中拉int。 現在,我很難告訴網格,當一個單元格的值大於“ 1”時,將其設為粗體。
這是我當前在專欄中檢查的代碼。 這是在表單加載事件上。
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.Font = new Font(dgvItems.Font.FontFamily,12, FontStyle.Bold);
foreach (DataGridViewRow row in dgvItems.Rows)
{
if (Convert.ToInt32(quantityDataGridViewTextBoxColumn.Text) > 1)
{
foreach (DataGridViewCell cell in row.Cells)
cell.Style.ApplyStyle(style);
}
}
嘗試這個
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.Font = new Font(dgvItems.Font.FontFamily, 12, FontStyle.Bold);
foreach (DataGridViewRow row in dgvItems.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
int result;
bool isInt = Int32.TryParse(cell.Value.ToString(), out result);
if (isInt && result > 1)
{
cell.Style = style;
}
}
}
--SJ
不幸的是,在Winforms DataGridViews
中沒有自動表達式可以對單元格進行樣式設置,因此您必須在代碼中進行。
您應該分解出樣式代碼,並在每次加載或更改數據時調用它。
這是一個例子。 您可能需要更改limit
參數的數據類型,並添加更多參數以允許使用更復雜的規則。
void styleCells(DataGridView dgv, string columnName, int limit)
{
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.Font = new Font(dgv.Font.FontFamily, 12, FontStyle.Bold);
foreach (DataGridViewRow row in dgv.Rows)
{
if (Convert.ToInt32(row.Cells[columnName].Value) > limit)
row.Cells[columnName].Style.ApplyStyle(style);
}
}
如果列名確實是quantityDataGridViewTextBoxColumn
可以這樣稱呼它:
styleCells(dgvItems, quantityDataGridViewTextBoxColumn, 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.