Меню

Окно сообщение об ошибке datagridview

I have a win form (c#) with a datagridview. I set the grid’s datasource to a datatable.

The user wants to check if some data in the datatable exists in another source, so we loop through the table comparing rows to the other source and set the rowerror on the datatable to a short message. The datagridview is not showing these errors. The errortext on the datagridviewrows are set, but no error displayed.

Am I just expecting too much for the errors to show and they only show in the context of editing the data in the grid?

I have been tinkering with this for a day and searched for someone that has posted a simalar issue to no avail — help!

Timothy Carter's user avatar

asked Nov 14, 2008 at 21:18

Check that AutoSizeRowsMode is set to DataGridViewAutoSizeRowsMode.None. I have found that the row Errortext preview icon is not displayed when AutoSizeRowsMode is not set to the default of none.

DataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None

sangram parmar's user avatar

answered May 6, 2009 at 10:13

Andrew's user avatar

AndrewAndrew

9677 silver badges8 bronze badges

2

This is a bit late for the original poster, but here what solved it for me…

Check the row height. If it’s less than 19 it will not draw the icon. Try setting it a bit higher to see if thats the problem.

grid.RowTemplate.Height = 22

answered Oct 29, 2010 at 15:27

1

If you set e.Cancel to True the icon does not display. Which does not let the user know that a problem exists on that line.

answered Jun 14, 2011 at 21:08

KenDog's user avatar

KenDogKenDog

1892 silver badges3 bronze badges

1

The DataGridView has to be visible at the time the ErrorText property is set.

sangram parmar's user avatar

answered Nov 20, 2012 at 21:04

Tim Fortune's user avatar

If you are using Visual Studio 2017 and your data is not bound to a datasource, then you have to set the ErrorText on the cell rather than the row, like this:

gvwWebsites.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "You have already used that address.";

pringi's user avatar

pringi

3,5825 gold badges35 silver badges43 bronze badges

answered Apr 21, 2017 at 9:35

Karin's user avatar

KarinKarin

1155 bronze badges

One more reason the error icon is not showing is, if the row header size is too small. By default, it is 46. If for some reason you set the row header to a smaller size, such as 30, the error icon will not display.

answered Nov 14, 2016 at 21:37

Norman Yuan's user avatar

Check dgv.ShowRowErrors property.

sangram parmar's user avatar

answered Aug 7, 2015 at 12:08

esc's user avatar

escesc

1982 silver badges4 bronze badges

I experienced similar issue when validating user input in the

private void gridGrid_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)

handler. The problem was I set e.Cancel=true in case of invalid input.

sangram parmar's user avatar

answered Nov 28, 2016 at 10:20

Bolek's user avatar

BolekBolek

513 bronze badges

0

In case someone else is still searching nowadays: The solution that worked for me was to re-assign the (same) DataSource to the DataGridView, and call the Refresh method on the grid after having set the RowError properties.

(VB.Net code:)

myDataGridView.DataSource = myDataSet.Tables(0) 
myDataGridView.Refresh()

After doing that, the newly assigned RowError’s were finally displayed.

answered Oct 18, 2011 at 10:45

Julien P's user avatar

Julien PJulien P

3233 silver badges8 bronze badges

1

I believe that the errors will only show on editing. What you could do is add a bool column to your DataTable, which drives the display of an image/custom column in the DataGridView, reflecting whether there is an error or not.

answered Nov 16, 2008 at 7:14

Robert Wagner's user avatar

Robert WagnerRobert Wagner

17.3k8 gold badges56 silver badges71 bronze badges

1

Send an ESC keystroke will force it to show (at least worked for me)

SendKeys.Send("{ESC}");

answered May 12, 2013 at 5:03

strongline's user avatar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
Public Class Form1
    Private Sub Load1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        With DataGridView1
            .Columns.Add("N", "Num")
            .Columns(0).ValueType = GetType(Double)
            .Columns.Add("D1", "Dat1")
            .Columns(1).ValueType = GetType(String)
            .Rows.Add({1253.256, "02.1.11"})
            .Rows.Add({2253.256, "233.5.2016"})
            .Rows.Add({3253.256, "2.11.2012"})
            .Rows.Add({4253.256, "23.12.2018"})
            .Rows.Add({5253.256, "27.10.2018"})
            .Rows.Add({6253.256, "22.12.2018"})
            .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        End With
        IncDate.sign = frm.OnlyMY
    End Sub
    Private Sub DataGridView1_CellPainting(sender As System.Object, e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
        If e.RowIndex > -1 AndAlso e.ColumnIndex = 1 AndAlso e.Value IsNot Nothing AndAlso e.Value.ToString.Length > 0 Then
            Dim ff As String = String.Empty
            Try
                Dim dd As New IncDate(e.Value)
                ff = dd.ToString
            Catch ex As Exception
                'MsgBox(ex.Message)
            End Try
            DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ff
        End If
    End Sub
    Private Sub DataGridView1_SortCompare(sender As System.Object, e As System.Windows.Forms.DataGridViewSortCompareEventArgs) Handles DataGridView1.SortCompare
        If e.Column.Index = 1 Then
            e.SortResult = IncDate.Compare(e.CellValue1.ToString(), e.CellValue2.ToString())
            e.Handled = True
        End If
    End Sub
End Class
 
Public Enum frm
    Fullshort
    FullLong
    OnlyMY
    OnlyY
End Enum
 
Public Class IncDate
    Private sDate As String
    Private dDate As Date
    Sub New()
        MyBase.new()
        sDate = String.Empty
        dDate = Nothing
    End Sub
    Sub New(DateString As String)
        Me.New()
        sDate = DateString
        getDate()
    End Sub
    Public Shared Property sign As frm
    Public Overrides Function ToString() As String
        Dim s As String = ""
        If dDate = Nothing Then Return s
        Select Case IncDate.sign
            Case frm.FullLong
                s = dDate.ToLongDateString
            Case frm.Fullshort
                s = dDate.ToShortDateString
            Case frm.OnlyMY
                s = String.Join(".", Format(dDate.Month, "00"), dDate.Year)
            Case frm.OnlyY
                s = dDate.Year
        End Select
        Return s
    End Function
    Public Function toDate() As Date
        Return dDate
    End Function
    Public Property sValue As String
        Get
            Return Me.ToString
        End Get
        Set(newvalue As String)
            sDate = newvalue
            getDate()
        End Set
    End Property
    Private Sub getDate()
        If sDate.Length > 0 Then
            If sDate.Length = 4 AndAlso IncDate.sign = frm.OnlyY Then sDate = "01." & sDate
            Try
                Dim culture As Globalization.CultureInfo = New Globalization.CultureInfo("ru-RU")
                dDate = Date.Parse(sDate, culture, Globalization.DateTimeStyles.None)
            Catch ex As Exception
                dDate = Nothing
            End Try
        Else
            dDate = Nothing
        End If
    End Sub
    Public Shared Function Compare(x As String, y As String) As Integer
        If x.Length = 0 AndAlso y.Length > 0 Then Return -1
        If x.Length > 0 AndAlso y.Length = 0 Then Return 1
        If x.Length = 0 AndAlso y.Length = 0 Then Return 0
        Dim culture As Globalization.CultureInfo = New Globalization.CultureInfo("ru-RU")
        Dim xdDate, ydDate As Date
        Select Case sign
            Case frm.FullLong, frm.Fullshort
                ydDate = Date.Parse(y, culture, Globalization.DateTimeStyles.None)
                xdDate = Date.Parse(x, culture, Globalization.DateTimeStyles.None)
            Case frm.OnlyMY
                Dim xm() As String = Split(x, ".")
                xdDate = New Date(CInt(xm(1)), CInt(xm(0)), 1)
                Dim ym() As String = Split(y, ".")
                ydDate = New Date(CInt(ym(1)), CInt(ym(0)), 1)
            Case frm.OnlyY
                xdDate = New Date(CInt(x))
                ydDate = New Date(CInt(y))
        End Select
        If xdDate > ydDate Then Return 1
        If xdDate < ydDate Then Return -1
        Return 0
    End Function
End Class

В этом примере показано, как вы можете обрабатывать ошибки DataGridView при изменении данных в элементе управления DataGridView. Пример Создание DataTable и привязка он в DataGridView в C# показывает, как использовать элемент управления DataGridView для отображения данных в DataTable, созданных в коде.

DataTable гарантирует, что его данные соответствуют его ограничениям. Например, DataTable не позволит программе добавить запись к данным, в которых отсутствует требуемое поле или это неправильный тип данных.

Если DataTable связан с DataGridView, и пользователь пытается ввести недопустимые данные, DataGridView отображает уродливое диалоговое окно, которое описывает ошибка и включает в себя трассировку мешка.

Если вы не хотите отображать диалоговое окно по умолчанию, вы можете поймать событие DataGrror элемента управления DataError. Ваш код может попытаться выяснить, что это неправильно, или, по крайней мере, сообщить пользователю, что данные недействительны в более дружественных условиях.

В этом примере используется следующий DataError обработчик событий, чтобы сообщить пользователю о возникновении проблемы.

// Произошла ошибка в данных.
private void dgvPeople_DataError(object sender,
    DataGridViewDataErrorEventArgs e)
{
    // Не делайте исключения, когда мы закончим.
    e.ThrowException = false;

    // Отображение сообщения об ошибке.
    string txt = "Error with " +
        dgvPeople.Columns[e.ColumnIndex].HeaderText +
        "nn" + e.Exception.Message;
    MessageBox.Show(txt, "Error",
        MessageBoxButtons.OK, MessageBoxIcon.Error);

    // Если это так, то пользователь попадает в эту ячейку.
    e.Cancel = false;
}

Источник: http://csharphelper.com/blog/2014/11/handle-datagridview-errors-in-c/

  • Remove From My Forums
  • Question

  • I am getting this error message whenever the focus on the datagridview and hit the «Exit» button to exit the Windows VB.net application. The message read:

    The following exception occured in teh DataGridView:

    System.IndexOutOfRangeException: Index xx does not have a value.

    at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)

    at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex)

    To replace the default dialog please handle the DataError event.

    What have I done wrong here? Thanks.

Answers

  • Hi pmak,

    I didn’t quite get your problem. It seems that you were trying to access some cells that do not exist when exiting the form. You can try to make a breakpoint on the exiting code to see where this exception actually happens.

    However, to replace or hide the error dialog, you can handle the DataError event of DataGridView control.

    Code Snippet

            private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)

            {

                //place your own dialog or do nonthing here

            }

    Let me know if this helps. If not, could you please show us more detailed information? Some code would be helpful.

    Best regards.
    Rong-Chun Zhang

    Windows Forms General FAQs
    Windows Forms Data Controls and Databinding FAQs

  • Remove From My Forums
  • Question

  • I am getting this error message whenever the focus on the datagridview and hit the «Exit» button to exit the Windows VB.net application. The message read:

    The following exception occured in teh DataGridView:

    System.IndexOutOfRangeException: Index xx does not have a value.

    at System.Windows.Forms.CurrencyManager.get_Item(Int32 index)

    at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex)

    To replace the default dialog please handle the DataError event.

    What have I done wrong here? Thanks.

Answers

  • Hi pmak,

    I didn’t quite get your problem. It seems that you were trying to access some cells that do not exist when exiting the form. You can try to make a breakpoint on the exiting code to see where this exception actually happens.

    However, to replace or hide the error dialog, you can handle the DataError event of DataGridView control.

    Code Snippet

            private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)

            {

                //place your own dialog or do nonthing here

            }

    Let me know if this helps. If not, could you please show us more detailed information? Some code would be helpful.

    Best regards.
    Rong-Chun Zhang

    Windows Forms General FAQs
    Windows Forms Data Controls and Databinding FAQs

Я видел много решений для этого, где задействована привязка данных, но у меня нет источника данных. В этом случае ячейка со списком применяется только к 1 строке (другие строки не имеют DataGridViewComboBoxCell).

Я установил DataGridViewComboCell следующим образом:

DataGridViewComboBoxCell cell = new DataGridViewComboBoxCell();
cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
cell.Items.AddRange(items.ToArray());   // items is List<string>

И я динамически повторно заполняю его позже следующим образом:

_cell.Items.Clear();
_cell.Items.AddRange(this.Data.ResponseOptions.Select( d => d.Description).ToArray());   
//d.Description is of type string

Но затем я получаю этот неприятный диалог, который говорит:

В DataGridView возникло следующее исключение: System.ArgumentException: недопустимое значение DataGridViewComboBoxCell. Чтобы заменить это диалоговое окно по умолчанию, обработайте событие DataError.

Между прочим, мало помогает сказать, что это не «действительно». Справедливо ли отправлять электронное письмо в MS о том, что Windows Forms недействительна?

Я попытался захватить свойство элементов ячейки и добавить строки, используя foreach() с вызовом Add(). Я все еще получаю диалог.

Я также пытался сдувать всю ячейку каждый раз, когда я хочу ее обновить, и воссоздавать новую DataGridViewComboCell с нуля. Я все еще получаю диалог.

Я также пытался вручную перезаписать значение столбца (успешно, когда у меня нет этой проблемы). Однако не исправил.

Кажется, я получаю это диалоговое окно только тогда, когда пытаюсь повторно заполнить элементы в комбинированной ячейке.

На данный момент я просто уничтожил метод DataError.

Какие-либо предложения?

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Окно ошибки виндовс 10 пнг
  • Окно ошибки windows пнг