在Datagridview中显示错误图标

时间:2013-05-23 14:49:04

标签: 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;

1 个答案:

答案 0 :(得分:2)

在DataGridViews中显示列错误有点古怪。为了使错误图标出现在单元格中,您不能使用e.Cancel = true,因为图标仅在单元格失去焦点后显示,这在为单元格设置e.Cancel时被阻止。

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

以下VB(我没有VS for C#for winforms进行测试,但如果你不能阅读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