【问题标题】:Show error to user in DataGridView在 DataGridView 中向用户显示错误
【发布时间】:2016-04-12 21:57:28
【问题描述】:

基本上,我拥有的是绑定到 DataGridView 的数据表。如果某些异常为真,我想要发生的是在数据网格中的每个单元格中显示错误类型工具提示。

我已经能够使用 CellValidating 在单元格中显示红色错误警报。问题是用户必须单击一个单元格,然后将该单元格移开焦点才能看到警报。

我还尝试在数据表上使用 ColumnChanging 来设置 RowError,但这根本不起作用。这是我尝试过的一些示例代码。

importGrid 是我的DataGridViewcsvData 是我的DataTable

private void importGrid_CellValidating(object sender, 
                                       DataGridViewCellValidatingEventArgs e)
{
  this.importGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText ="Drive Letter in use";
}

private void csvData_ColumnChanging(object sender, 
                                    System.Data.DataColumnChangeEventArgs e)
{
   e.Row.RowError = "test error";
   e.Row.SetColumnError(e.Column, "test error 2");
}

【问题讨论】:

    标签: c# datagridview datatable


    【解决方案1】:

    为什么不在绑定后遍历所有RowsCells,测试条件并设置ErrorText

    foreach(DataGridViewRow row in DGV.Rows)
    foreach(DataGridViewCell cell in row.Cells) 
        if (yourCondition) cell.ErrorText = yourErrorText;
    

    【讨论】:

      【解决方案2】:

      有两个事件您可能会觉得有用。 RowErrorTextNeededCellErrorTextNeeded。这是我的一个项目中使用RowErrorTextNeeded 的示例。当行变为可见或发生任何更改时,DataGridView 会触发此事件。

      private void dataGridView1_RowErrorTextNeeded( object sender, DataGridViewRowErrorTextNeededEventArgs e )
      {
          DataGridView dataGridView = sender as DataGridView;
          if( dataGridView != null )
          {
              DataRowView view = dataGridView.Rows[e.RowIndex].DataBoundItem as DataRowView;
              if( view != null )
              {
                  if( view.Row[invColorColumn] == DBNull.Value )
                      e.ErrorText = "Color code is missing from part database.";
                  else if( view.Row[invThickColumn] == DBNull.Value )
                      e.ErrorText = "Thickness is missing from part database.";
                  else if( view.Row[invWidthColumn] == DBNull.Value )
                      e.ErrorText = "Width is missing from part database.";
                  else if( view.Row[invHeightColumn] == DBNull.Value )
                      e.ErrorText = "Height is missing from part database.";
                  else 
                      e.ErrorText = String.Empty;
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        • 2020-03-18
        相关资源
        最近更新 更多