Skip to main content
 首页 » 编程设计

c#之DataGridView 同一列中的不同单元格格式可能吗

2024年02月13日12lonelyxmas

再次需要这个很棒的社区的帮助。

我有一个带有 DataGridView 的 WinForms 应用程序来显示一些数据。 特别是有两列对我很重要。一是“单位”,二是“值(value)”。 Unit 在 format 中有字符串,Value 有数值。我想根据单位是什么来格式化每个 DataGridViewRow 中的值。例如:如果单位是“piece”,我需要 Value 是 int(没有小数位)。如果单位是“mm”,我需要将值除以 1000 并显示两 (2) 位小数,并将单位更改为“m”...希望您能理解。还有一些图形解释:

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

处理这个问题的正确方法是什么? 感谢您的帮助。

请您参考如下方法:

您将需要处理 CellFormatting() 事件。在这里,您可以访问当前行和列。

在这种情况下,您可以访问 DataGridViewCellFormattingEventArgs 类型中的以下属性:

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

因此,您可以使用 RowIndex 属性在您的 datasource 中查找值,以获得条件格式的其他列值。

我现在还没有 VS,但像这样:

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,您可能需要处理其中的任何异常。