我有一個錯誤問題“索引超出范圍。必須是非負數并且小于集合的大小”當我輸入一個數值為“1”的值時出現錯誤并且該值不在datagridview 中的“代碼”列。有沒有最好的推薦?
Public x As Integer
Dim source1 As New BindingSource()
Private Sub TextBox2_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Back Then
source1.Filter = ""
TextBox1.Clear()
Else
If e.KeyCode = Keys.Enter Then
source1.Filter = "CODE = '" & Replace(TextBox2.Text, "'", "") & "'"
x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
txtCODE.Text = DataGridView1.Rows(x).Cells(0).Value.ToString()
Dim dte = DataGridView1.Rows(x).Cells(1).Value.ToString()
If dte <> Nothing Then
txtDTE.Text = CDate(dte)
Else
'CLEAR txtDTE if dt <> nothing
txtDTE.Clear()
End If
txtQTY.Text = DataGridView1.Rows(x).Cells(2).Value.ToString()
txtPRICE.Text = DataGridView1.Rows(x).Cells(3).Value.ToString()
txtPRICE.Text = String.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US"), "{0:N0}", Double.Parse(txtPRICE.Text))
If source1.Count <= 0 Then
source1.Filter = ""
TextBox2.Clear()
MsgBox("No Result Found!", MsgBoxStyle.Exclamation)
End If
End If
End If
End Sub


uj5u.com熱心網友回復:
我通過添加檢查以確保當前行的索引有效來修復它。
Public x As Integer
Dim source1 As New BindingSource()
Private Sub TextBox2_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Back Then
source1.Filter = ""
TextBox1.Clear()
Else
If e.KeyCode = Keys.Enter Then
source1.Filter = "CODE = '" & Replace(TextBox2.Text, "'", "") & "'"
x = DataGridView1.Rows.IndexOf(DataGridView1.CurrentRow)
***If x >= 0 And x <= DataGridView1.Rows.Count - 1 Then*** 'ADD THIS CODE SOLUTION FOR ME
txtCODE.Text = DataGridView1.Rows(x).Cells(0).Value.ToString()
Dim dte = DataGridView1.Rows(x).Cells(1).Value.ToString()
If dte <> Nothing Then
txtDTE.Text = CDate(dte)
Else
'CLEAR txtDTE if dt <> nothing
txtDTE.Clear()
End If
txtQTY.Text = DataGridView1.Rows(x).Cells(2).Value.ToString()
txtPRICE.Text = DataGridView1.Rows(x).Cells(3).Value.ToString()
txtPRICE.Text = String.Format(System.Globalization.CultureInfo.GetCultureInfo("en-US"), "{0:N0}", Double.Parse(txtPRICE.Text))
End If
End If
End If
If source1.Count <= 0 Then
source1.Filter = ""
TextBox2.Clear()
MsgBox("No Result Found!", MsgBoxStyle.Exclamation)
End If
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/461160.html
