c# - 在 Datagridview 中显示错误图标

标签 c# asp.net

我想在触发此事件时在 datagridview 特定单元格上显示错误文本和图标

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)

我该怎么做?

我尝试了以下方法:

if (int.Parse(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()) > nbsstatus)

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Max Social Status is " + nbsstatus;
e.cancel=true;

最佳答案

在 DataGridViews 中显示列错误有点奇怪。为了使错误图标出现在单元格中,您不能使用 e.Cancel = true,因为该图标仅在单元格失去焦点后才显示,而为单元格设置 e.Cancel 时可以防止这种情况。

为了解决此问题,RowValidating 事件必须循环遍历所有单元格以确定是否已标记错误,如果是,则必须设置 e.Cancel = true,以便用户无法离开当前行,直到出现错误( s) 已解决。

以下 VB(我没有用于 winforms 的 VS for C# 进行测试,但如果您无法阅读 VB,则可以使用免费的 VB 到 C# 转换器之一):

Private Sub DataGridView1_CellBeginEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
    Dim dgv As DataGridView = sender
    dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = ""
    dgv.Rows(e.RowIndex).ErrorText = ""
End Sub

Private Sub DataGridView1_CellValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
    Dim dgv As DataGridView = sender
    ' these edits are for illustration purposes only
    Select Case e.ColumnIndex
        Case 0
            If e.FormattedValue = "NO" Then
                dgv.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "No - Column Error Message"
                dgv.Rows(e.RowIndex).ErrorText = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText
            End If
        Case 1
            If e.FormattedValue = "YES" Then
                DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = "Yes - Column Error Message"
                dgv.Rows(e.RowIndex).ErrorText = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText
            End If
        Case Else
            e.Cancel = False
    End Select

End Sub

Private Sub DataGridView1_RowValidating(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.RowValidating
    Dim dgv As DataGridView = sender
    For Each Col As DataGridViewColumn In dgv.Columns
        If Not String.IsNullOrEmpty(dgv.Rows(e.RowIndex).Cells(Col.Index).ErrorText) Then
            dgv.CurrentCell = dgv(Col.Index, e.RowIndex) 'set focus
            e.Cancel = True
        End If
    Next
End Sub

关于c# - 在 Datagridview 中显示错误图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717124/

相关文章:

asp.net - 母版页使用母版页和继承

asp.net - @Html.DisplayNameFor 不显示数据 MVC5

c# - 有没有一种方法可以将 4 个控件分组到一个 UserControl 或模板中,并在父 UserControl 中使用它并将它们与 MVVM 绑定(bind)?

asp.net - Repeater 内的 Gridview

c# - 在 UpdatePanel 中回发后添加用户控件,然后是另一个回发 - 如何在用户控件中获取控件的输入?

c# - 将 Bootstrap 设计添加到网络表单

c# - EKEventStore 访问请求在 iOS 10 上崩溃

c# - 代码契约、继承和里氏原理

c# - 在 UWP、MVVM 中实现周期性进程

c# - 通用可空枚举