DataGridView Different cell formatting in same col

2019-08-04 04:02发布

问题:

Again need help from this awsome comunity.

I have a WinForms app with DataGridView to display some data. There are especcialy two columns that are important to me. One is "Unit" and the second one is "Value". Unit has strings inside format and Value has numeric values. I would like to format the Value in each DataGridViewRow depending on what the Unit is. For example: if unit is 'piece', I need Value to be int (no decimal places). If unit is 'mm', I need to divide Value with 1000 and show two (2) decimal places and also change Unit to 'm'... Hope you understand. Also some graphic interpretation:

Unit   Value    ----> Wanted display format ----> Unit   Value
piece  100,00                                     piece   100
mm     10000,00                                   m       10,00
g      100000,00                                  kg      100,00

What would be the right way to aproach this? Thank you for your help.

回答1:

You will need to handle the CellFormatting() event. In here, you can get access to the current row and column.

In this event you have access to the following properties in the DataGridViewCellFormattingEventArgs type:

Public property CellStyle
Public property ColumnIndex
Public property DesiredType
Public property FormattingApplied   
Public property RowIndex    
Public property Value   

Thus you can use the RowIndex property to look up the value in your datasource to get the other columns value for your conditional formatting.

I haven't got VS handy at the moment but something like:

private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if (e.ColumnIndex == ValueColIndex)
  {
    string unit = datasource.Rows[e.RowIndex][ValueColIndex].ToString();
    switch(unit)
    {
      case "piece": e.Value = Convert.ToInt32(e.Value).ToString();
       e.FormattingApplied = true;
       break;
      case "mm": e.Value = string.Format("{0:00}", Convert.ToDouble(e.Value) / 1000);
       e.FormattingApplied = true;
       break;
      //etc
    }
  }
}

PS, you may need to handle any exceptions in there.