Paolo Nicolas Tansengco Paolo Nicolas Tansengco - 5 months ago 17
SQL Question

How to retrieve data from database to textbox

Need help on my codes. I need to show my data(Firstname and Lastname) from my database to a textbox but i can't figure out the code. Need help. Thnx. Here's the error:

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.

and the code: error at line 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
txtLname.Text = .GetValue("LastName")
txtFname.Text = .GetValue("FirstName")
End With
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
End Sub


Maybe you should use DataGridViewCellEventArgs.RowIndex instead of 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