How to set “Unavailable” word for null values in DataGridView

大城市里の小女人 提交于 2020-01-05 05:47:30

问题


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:

  1. Set NullValue property of DefaultCellStyle of the column. It sets the cell display value corresponding to a cell value of DBNull.Value or null.
  2. Use CellFormatting event and set e.Value when the value of cell is DBNull.Value or null

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!