问题
I have an employees
table in which first number is set as not null and second number that can be **null* so when I call the employees
information to view their information in DataGridView
the null values appear as empty cells but I want to show "Unavailable" word instead of the empty cell , so how can I do this?
回答1:
You can use either of these options:
- Set NullValue property of
DefaultCellStyle
of the column. It sets the cell display value corresponding to a cell value ofDBNull.Value
ornull
. - Use
CellFormatting
event and sete.Value
when the value of cell isDBNull.Value
ornull
Example 1
this.dataGridView1.Columns[1].DefaultCellStyle.NullValue = "Unavailable";
Example 2
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if (e.Value == DBNull.Value || e.Vallue == null)
e.Value = "Unavailable";
}
回答2:
Change your Select
statement to something like this (use CASE WHEN
):
SELECT Id, CASE WHEN SecondNumber IS NULL THEN 'Unavailable' ELSE SecondNumber END AS SecondNumber
FROM yourTable
回答3:
This solution would also include an extension method so please make the following extension method.
this is what we will need to set the values of the grid in a more clean way (optional though)
public static void ApplyAction<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var entity in source)
{
action(entity);
}
}
now all you have to do is going to be the following :
dataGridView1.Rows.OfType<DataGridViewRow>().Where(c => c.Cells[ColumnName.Index].Value == null).ApplyAction(new Action<DataGridViewRow>(c => c.Cells[ColumnName.Index].Value = "Unavailable"));
来源:https://stackoverflow.com/questions/39931566/how-to-set-unavailable-word-for-null-values-in-datagridview