how to change text in datagridview text on condition .

[亡魂溺海] 提交于 2019-12-31 03:01:17

问题


I am using a datagridview and I want to display do conditional formatting means when I get for a cell M then I want to display Married.I try this but not sucess.

Here is my code:

private void masterDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
      {
          try
          {
              for (int i = 0; i <= masterDataGridView.Rows.Count - 1; i++)
              {
                  String Value = masterDataGridView.Rows[i].Cells[17].Value.ToString();
                  if (Value == "M")
                  {
                      e.Value = "Male";
                  }
              }
          }
          catch (Exception ex)
          {

          }
      }

回答1:


You're trying to use the .CellFormatting event with for loop statement which is not the proper way.

The CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event. This event also occurs when the cell FormattedValue is retrieved or its GetFormattedValue method is called.

So every time the cell is painted, the for loop is running.

Try this:

private void masterDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    try
    {
        if (e.ColumnIndex >= 17 && e.ColumnIndex <= 24)
        {
            if (e.Value == "M")
                e.Value = "Married";
            else
                e.Value = "Not Married";
        }
    }
    catch (Exception ex)
    {

    }
}



回答2:


After a little work this code work for me very fine . I am posting it may be any other can use the code

private void masterDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{

    if (masterDataGridView.Columns[e.ColumnIndex].Name.Equals("Gender"))
                      {
                          string _val = e.Value as string;
                          if (_val == null)
                              return;


                          switch (_val)
                          {
                              case  "M" :
                                  e.Value = "Male";
                                  break;
                              case "F":
                                  e.Value = "Female";
                                  break;

                          }

                      }
}

Chearss ....



来源:https://stackoverflow.com/questions/15110193/how-to-change-text-in-datagridview-text-on-condition

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