代码之家  ›  专栏  ›  技术社区  ›  Rakha

在Datagridview中使用DataTable时更改DefaultCellStyle

  •  0
  • Rakha  · 技术社区  · 7 年前

    以下是上下文:

    我以前使用过:

    $datagridviewInfo.Rows.Add("123", "456")
    

    要填充DataGridView,但我注意到,如果DataGridView不使用“DataTable”作为数据源,我就无法将其导出到CSV。

    现在我正在创建一个DataTable并将我的行添加到这个对象中。我现在可以成功导出到CSV。

    $button1_Click={
     $RowNomPoste = $datagridviewInfo.Rows.Add("Poste", "$poste est inaccessible.")
     $datagridviewInfo.Rows.Item($RowNomPoste).DefaultCellStyle.BackColor = "Red"
    }
    

    它可以工作,并给我那一行以红色突出显示。但是,该方法不使用DataTable,因此不好,因为稍后我无法导出到CSV。

    $button2_Click={
     $tableInfoPoste = New-Object system.Data.DataTable "TableInfoPoste"
    
     $tableInfoPoste.Columns.Add("Propriété")
     $tableInfoPoste.Columns.Add("Valeur")
    
     $datagridviewInfo.DataSource = $tableInfoPoste
    
     $RowNomPoste = $tableInfoPoste.Rows.Add("Poste", "$poste est inaccessible.")
    
     $tableInfoPoste.Rows.Item($RowNomPoste).DefaultCellStyle.BackColor = "Red"
    
    }
    

    它添加了行,但不允许我更改其DefaultCellStyle。

     Cannont convert argument «index» («System.Data.DataRow»)  «get_Item» to type «System.Int32»: «
    ERROR: Cannot convert the value «System.Data.DataRow» of type «System.Data.DataRow» to type «System.Int32».»»
    

    为什么它在使用第一种直接向DataGridView添加行的方法时有效,而在使用DataTable时无效? 如何使用DataTable但仍正确设置行的样式?

    非常感谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Rakha    7 年前

    我在RowPrePaint活动中使用了如下内容:

    $datagridviewInfo_RowPrePaint=[System.Windows.Forms.DataGridViewRowPrePaintEventHandler]{
     if (($datagridviewInfo.Rows[$_.RowIndex].Cells[1].Value) -like "*inaccessible*")
     {
      $datagridviewInfo.Rows[$_.RowIndex].DefaultCellStyle.BackColor = 'red'
     }
    
    
    }
    

    https://social.technet.microsoft.com/Forums/windowsserver/en-US/6cb6a5be-08bd-47d4-8783-66d57fc26ead/change-defaultcellstyle-when-using-a-datatable-in-datagridview?forum=winserverpowershell