我有一个 Datagridview
列,其值为 int
。我有一个值状态条件,if(status == 1)
然后将文本更改为 Active
,否则将文本更改为 Not Active
。
任何帮助将不胜感激。
private void bindListToGridView(List<Employee> list)
{
// DataTable dt2 = convertListToDataTable(list);
// more codes here.
using (dt2)
{
// more codes here.
dataGridView1.Columns[8].Name = "Status";
dataGridView1.Columns[8].HeaderText = "Status";
dataGridView1.Columns[8].DataPropertyName = "status";
dataGridView1.DataSource = dt2;
}
}
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
string columnName = dataGridView1.Columns[e.ColumnIndex].Name;
if (columnName == "Status")
{
int value = (int)dataGridView1.Rows[e.RowIndex].Cells["Status"].Value;
if (value == 1)
{
// set the cell text = Active
}
else
{
// set the cell text = Not Active
}
}
}
最佳答案
为避免更改基础整数值,您可以将单元格的格式设置为所需的文本:
if (value == 1)
{
dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Active";
}
else
{
dataGridView1.Rows[e.RowIndex].Cells["Status"].Style.Format = "Not Active";
}
或者更简单,正如 LarsTech 指出的那样,等价地设置:
e.Value = "Active";
这是有效的,因为我们已经在 CellFormatting
事件处理程序中,并且 DataGridViewCellFormattingEventArgs
的 Value
属性是格式化后的转换值。
关于c# - 更改 dataGridView CellFormatting 中单元格的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142611/