2016-09-12 19 views
0

コードのヘルプが必要です。自分のデータベース(FirstnameとLastname)をデータベースからテキストボックスに表示する必要がありますが、コードを特定できません。助けが必要。 Thnx。ここではエラーがあります:データベースからテキストボックスにデータを取り出す方法

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

やコード:行5

Private Sub dg1_RowEnter(sender As Object, e As DataGridViewCellEventArgs) Handles dg1.RowEnter 
    With cmd 
     .Connection = cn 
     .CommandText = "SELECT ID, LastName, FirstName FROM tblMembers WHERE ID = @ID" 
     .Parameters.Add(New SqlClient.SqlParameter("@ID", SqlDbType.Int)).Value = dg1.SelectedRows(0).Cells(0).Value 
    End With 
    dr = cmd.ExecuteReader 
    With dr 
     .Read() 
     txtLname.Text = .GetValue("LastName") 
     txtFname.Text = .GetValue("FirstName") 
    End With 
    Try 
     txtContactNo.Text = dg1.Item(2, e.RowIndex).Value 
     txtAddress.Text = dg1.Item(3, e.RowIndex).Value 
     dtpBirthday.Text = dg1.Item(4, e.RowIndex).Value 
     dtpBaptism.Text = dg1.Item(5, e.RowIndex).Value 
     txtMinistry.Text = dg1.Item(6, e.RowIndex).Value 
     Dim ms As New MemoryStream(changePhoto(CInt(dg1.SelectedCells(0).Value))) 
     PictureBox1.Image = Image.FromStream(ms) 
    Catch ex As Exception 

    End Try 
    cn.Close() 
End Sub 
+0

あまりを使用する必要がありますでエラーここで、私はあなたがこれをデバッグしようとするとSelectedRowsが見つからないと思う。 –

+0

@SeanLange私もそうだと思います。これを修正する方法はありますか? –

答えて

0

たぶん、あなたは、細部の形でDataGridViewCellEventArgs.RowIndex代わりのdg1.SelectedRows(0)

This event occurs before the CurrentRow property is updated. To retrieve the index of the newly-entered row, use the DataGridViewCellEventArgs.RowIndex property within the event handler. from Microsoft

.Parameters.Add(New SqlClient.SqlParameter("@ID", SqlDbType.Int)).Value = dg1(0, e.RowIndex).Value 
+0

ありがとうございました。しかし、今私は接続に問題があります。 .executereaderにはオープンな接続が必要だと言われていますが、接続を開くと、cn.Open()を追加すると接続が閉じられないというメッセージが表示されます。 –

+0

使用後にすべての接続が閉じていることを確認できますか?また、 'cn.state'をデバッグモードでチェックして、接続の状況を確認してください。 – Prisoner

+0

それは働いている、ちょうどいくつかの微調整をした。しかし、助けてくれてありがとう。 :) –

関連する問題