There is no row at position 0 and System.IndexOutOfRangeException - sql

Error :
An unhandled exception of type 'System.IndexOutOfRangeException'
occurred in System.Data.dll and also showing a :There is no row at
position 0
Dim mycn As New SqlConnection(connection)
Dim DT As New DataTable
mycn.Open()
Dim Adapter As New SqlDataAdapter("SELECT * FROM tblUser where username ='" & txtRet.Text & "'", connection)
Adapter.Fill(DT)
txtUserID.Text = DT.Rows(0)("aid").ToString()
txtFirstName.Text = DT.Rows(0)("fname").ToString()
txtMiddleName.Text = DT.Rows(0)("mi").ToString()
txtLastName.Text = DT.Rows(0)("lname").ToString()
DateOfBirthDateTimePicker.Text = DT.Rows(0)("bday").ToString()
txtAge.Text = DT.Rows(0)("age").ToString()
cmbGender.Text = DT.Rows(0)("gender").ToString()
txtContactNo.Text = DT.Rows(0)("contactno").ToString()
txtEmail.Text = DT.Rows(0)("email").ToString()
txtAddress.Text = DT.Rows(0)("address").ToString()
txtUsernamePS.Text = DT.Rows(0)("username").ToString()
txtPasswordPS.Text = DT.Rows(0)("password").ToString()
rtbSQuestions.Text = DT.Rows(0)("squestion").ToString()
rtbAnswer.Text = DT.Rows(0)("answer").ToString()
Dim bytBLOBData() As Byte = _
DT.Rows(0)("userimage")
Dim stmBLOBData As New MemoryStream(bytBLOBData)
UserPictureBox.Image = Image.FromStream(stmBLOBData)
mycn.Close()

This error indicates that no rows were returned and since you're trying to get the first row (...DT.Rows(0)...) it is throwing the error.
My first suggestion would be to wrap your code in Using statements for all of the objects that implement iDisposable. My second suggestion would be to utilize a parameterized query. My last suggestion would be to check if Rows(0) exists before trying to access it.
Here is a quick example:
'Declare the connection object
Dim con As SqlConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = New SqlConnection(connection)
'Create a new instance of the command object
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM [tblUser] WHERE [username]=#username;", con)
'Parameterize the query
cmd.Parameters.AddWithValue("#username", txtRet.Text)
'Open the connection
con.Open()
'Declare a new adapter to fill the data table
Dim adapter As SqlDataAdapter = New SqlDataAdapter(cmd)
adapter.Fill(DT)
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If DT.Rows.Count > 0 Then
txtUserID.Text = DT.Rows(0)("aid").ToString()
txtFirstName.Text = DT.Rows(0)("fname").ToString()
txtMiddleName.Text = DT.Rows(0)("mi").ToString()
txtLastName.Text = DT.Rows(0)("lname").ToString()
DateOfBirthDateTimePicker.Text = DT.Rows(0)("bday").ToString()
txtAge.Text = DT.Rows(0)("age").ToString()
cmbGender.Text = DT.Rows(0)("gender").ToString()
txtContactNo.Text = DT.Rows(0)("contactno").ToString()
txtEmail.Text = DT.Rows(0)("email").ToString()
txtAddress.Text = DT.Rows(0)("address").ToString()
txtUsernamePS.Text = DT.Rows(0)("username").ToString()
txtPasswordPS.Text = DT.Rows(0)("password").ToString()
rtbSQuestions.Text = DT.Rows(0)("squestion").ToString()
rtbAnswer.Text = DT.Rows(0)("answer").ToString()
End If

Related

Save and Update from Datagridview to Access Database

i've been fumbling with this problem for a while now. am trying to update/insert into my access database data from a datagridview on a form.
i've a maskedtextbox that i've masked to suit my primary key. when the mask is completed then automatically, records are read from the database to the textboxes and datagridview as shown in the attached picture.
i did that with this code
If STHN_ID.MaskCompleted = True Then
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
'da = New OleDbDataAdapter("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn) 'Change items to your database name
'da.Fill(ds)
'Dim view As New DataView(tables(0))
'source1.DataSource = view
'DependantView.DataSource = view
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("Select [DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", MyConn)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
'connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DependantView.DataSource = myTable
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
my headache now is to update/insert into the database when records are added/edited in the datagridview based on the STHN_ID entered in the maskedtextbox. any help would be really appreciated.
sample
this is how i got it done!
on maskedtextbox with mask completed this is the code to read from database and load datagridview ...........
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
con = New OleDbConnection
con.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\PRINCE\Documents\STHNDatabase.accdb")
con.Open()
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "SELECT * FROM PersonalData WHERE (STHN_ID='" & STHN_ID.Text & "')"
Dim STHNCmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = STHNCmd.ExecuteReader()
If dr.HasRows = -1 Then
While dr.Read
Fname.Text = dr("Fname").ToString
LName.Text = dr("Lname").ToString
Oname.Text = dr("Onames").ToString
DOB.Text = dr("DOB")
Title.Text = dr("Title").ToString
salaryType.Text = dr("SalaryType").ToString
StaffID.Text = dr("StaffNo").ToString
SSN.Text = dr("SSN").ToString
DateEngaged.Text = dr("DateEngaged")
Category.Text = dr("Category").ToString
Rank.Text = dr("Rank").ToString
StaffDept.Text = dr("StaffDept").ToString
PersonalData.PassportPic.BackgroundImageLayout = ImageLayout.Stretch
Dim bits As Byte() = CType(dr("PassportPic"), Byte())
Dim memo As New MemoryStream(bits)
Dim myimg As New Bitmap(memo)
PassportPic.Image = myimg
Dim connection As New OleDbConnection
connection.ConnectionString = connString
adapt = New OleDbDataAdapter("Select [DependentID],[DependantFname],[DependantLname],[DependantOname],[DependantDOB],[Relationship],[STHN_ID] FROM [DependantData] WHERE [STHN_ID]='" & STHN_ID.Text & "'", con)
ds = New DataSet
adapt.Fill(ds, "DependantData")
DependantView.DataSource = ds.Tables(0)
End While
myConnection.Close()
Else
MessageBox.Show("No Records for the STHN_ID entered", "", MessageBoxButtons.OK, MessageBoxIcon.Information)
myConnection.Close()
STHN_ID.Focus()
End If
Catch ex As Exception
MsgBox(ex.Message)
myConnection.Close()
End Try
and on the SaveButton Click this is the code.....
Private Sub SaveBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn.Click
Try
builder = New OleDbCommandBuilder(adapt)
adapt.Update(ds, "DependantData")
MsgBox("Updated Successfully")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
thanks once again. really appreciate it

Populating Datagrid

I am creating a pageant scoring system,
I have this functions for populating my datagridview's first column using query:
Public Sub searchContestant()
If comboCategory.SelectedIndex <> 0 Then
Dim id As Integer = Login.JudgeBindingSource1.Current("Cont_id")
Dim critID As Integer = Convert.ToInt32(lblID.Text)
'search the contest record by the contest_id
Dim con As New SqlConnection
Dim reader As SqlDataReader
Dim reader2 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
DataGridView1.Rows.Clear()
Try
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & critID & "' ", con)
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
' Execute Query
reader = cmd.ExecuteReader()
nc.Name = "Contestants"
nc.Width = 250
nc.ReadOnly = True
DataGridView1.Columns.Add(nc)
While reader.Read()
nc = New DataGridViewTextBoxColumn
nc.Name = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.HeaderText = "(" & reader.GetString(2) & "%)" & reader.GetString(1)
nc.Width = 150
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
Try
'populate contestant rows
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd2 As New SqlCommand("SELECT * from Contestant where Cont_id = '" & id.ToString() & "' ", con)
con.Open()
reader2 = cmd2.ExecuteReader()
While reader2.Read()
nc = New DataGridViewTextBoxColumn
nc.Width = 100
DataGridView1.Rows.Add(reader2.GetString(2).ToString())
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End If
End Sub
And for succeeding columns :
Public Sub searchCriteria()
Dim con As New SqlConnection
Dim reader4 As SqlDataReader
Dim dt = New DataTable()
Dim nc As New DataGridViewTextBoxColumn
DataGridView1.Columns.Clear()
Try
'populate Criteria
con.ConnectionString = "Data Source=BROWNIE\SQLEXPRESS;Initial Catalog=PSS;Integrated Security=True"
Dim cmd As New SqlCommand("SELECT * from Criteria where Cat_id = '" & lblID.Text & "' ", con)
con.Open()
reader4 = cmd.ExecuteReader
While reader4.Read
nc = New DataGridViewTextBoxColumn
nc.Name = reader4.GetString(1).ToString & Chr(13) & reader4.GetString(2).ToString & "%"
nc.Width = 100
DataGridView1.Columns.Add(nc)
End While
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
con.Close() 'Whether there is error or not. Close the connection. '
End Try
End Sub
This is the output:
And everytime a judge login, I insert data into the system with this function:
Public Sub makeTransaction()
Dim con2 As New SqlConnection
'get the judge id upon logging in
Dim judgeID = Login.JudgeBindingSource1.Current("Judge_id")
'get the contest id of the judge
Me.JudgeTableAdapter.FillByJudgeID(Me.PSSDataSet.Judge, judgeID)
Dim JudgeContestid = Login.JudgeBindingSource1.Current("Cont_id")
Me.ContestantTableAdapter.FillByContestID(Me.PSSDataSet.Contestant, JudgeContestid)
'get the contestant id
Me.ContestTableAdapter.FillByContestID(Me.PSSDataSet.Contest, JudgeContestid)
Dim contestID As Integer = ContestBindingSource.Current("Cont_id")
'get the category of the contest
Me.CategoryTableAdapter.FillByContestID(Me.PSSDataSet.Category, Convert.ToInt32(contestID))
For Each Category As DataRow In Me.PSSDataSet.Category.Rows
Me.CriteriaTableAdapter.FillByCategoryID(Me.PSSDataSet.Criteria, Category("Cat_id"))
For Each Contestant As DataRow In Me.PSSDataSet.Contestant.Rows
For Each Criteria As DataRow In Me.PSSDataSet.Criteria.Rows
TransactionsTableAdapter.Insert(JudgeContestid, Contestant("Con_id"), Criteria("Cri_id"), 0)
Next
Next
Next
End Sub
Now my problem is, how can I populate the datagrid using the data recently made by MakeTransaction() function?

Executing update query inside loop

cmd = New SqlCommand("select enrollment,total_fee,discount,net_fee from stu_dtl", openConnection())
' dr = cmd.ExecuteReader
adpt = New SqlDataAdapter(cmd)
adpt.Fill(ds, "stu_dtl")
dt = ds.Tables("stu_dtl")
For i = 0 To dt.Rows.Count - 1
cmd = New SqlCommand("update stu_dtl set net_fee = '" & (Val(dt.Rows(i).Item("total_fee")) - Val(dt.Rows(i).Item("discount"))) & "' where enrollment = '" & dt.Rows(i).Item("enrollment") & "'", openConnection())
cmd.ExecuteNonQuery()
Next
when I execute this code for more than 150 records "Nothing happens"......what am i doing wrong??is there any other way to update??
I'm not sure what you are doing wrong. But try this code. If an error occur it ensure rollback of the database. Note that I assume that the datatype of the net_fee and enrollment columns are Integer.
Using connection As SqlConnection = New SqlConnection("TODO: Set connection string.")
Dim table As DataTable = New DataTable("stu_dtl")
Dim [error] As Exception = Nothing
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "SELECT [enrollment], [total_fee], [discount], [net_fee] FROM [stu_dtl];"
Using adapter As New SqlDataAdapter(command)
adapter.Fill(table)
End Using
End Using
Using transaction As SqlTransaction = connection.BeginTransaction()
Try
Dim net_fee As Integer = 0
Dim enrollment As Integer = 0
For Each row As DataRow In table.Rows
net_fee = (CInt(row.Item("total_fee")) - CInt(row.Item("discount")))
enrollment = CInt(row.Item("enrollment"))
Using command As SqlCommand = connection.CreateCommand()
command.CommandText = "UPDATE [stu_dtl] SET [net_fee] = #net_fee WHERE [enrollment] = #enrollment;"
command.Parameters.AddWithValue("#net_fee", net_fee)
command.Parameters.AddWithValue("#enrollment", enrollment)
command.ExecuteNonQuery()
End Using
Next
transaction.Commit()
Catch ex As Exception
[error] = ex
transaction.Rollback()
End Try
End Using
If (Not table Is Nothing) Then
table.Dispose()
table = Nothing
End If
If (Not [error] Is Nothing) Then
Throw [error]
End If
End Using
Edit
Come to think of it, you might want to change the net_fee column to a computed column. The formula would simply be ([total_fee] - [discount]).

Error "Child list for field [Sheet1$] cannot be created" when loading data from excel to datagridview

I am trying to fill the DataGridView (grvExcelData in this case) with data from an excel file. But I am getting the following error:
"Child list for field [Sheet1$] cannot be created"
Below is my code fragment where I am trying to fill the data grid view. Also I am using Visual Studio 2010 for programming
Thanks for your help in advance
Public Sub fillgrid()
Dim conn1 As String
conn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filenamepath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
Dim connection As OleDbConnection = New OleDbConnection(conn1)
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection)
Dim ds As DataSet = New DataSet()
Dim emptyfile As String = "The file does not have any records for inserting."
Dim selectCmd As OleDbCommand = New OleDbCommand()
selectCmd.Connection = connection
selectCmd.CommandText = "SELECT * FROM [Sheet1$]"
If connection.State = ConnectionState.Closed Then
connection.Open()
End If
da.SelectCommand = selectCmd
Dim dsCounter As Integer = da.Fill(ds, "[Sheet1$]")
If dsCounter = 0 Then
MessageBox.Show(emptyfile, "dsCounter")
End If
grvExcelData.DataSource = ds
grvExcelData.DataMember = "Sheet1"
grvExcelData.SelectionMode = DataGridViewSelectionMode.FullRowSelect
da.Dispose()
If connection.State = ConnectionState.Open Then
connection.Close()
connection.Dispose()
End If
End Sub
Change
grvExcelData.DataMember = "Sheet1"
to
grvExcelData.DataMember = "[Sheet1$]"

how to simplify codes

I have a next button.
theres no error i just want to simplify
Try
lblcat.Text = ds.Tables("evaluation").Rows(cat)("QuestionCategory")
txt1.Text = ds.Tables("evaluation").Rows(CurrentRow)("Question")
txt2.Text = ds.Tables("evaluation").Rows(CurrentRow + 1)("Question")
txt3.Text = ds.Tables("evaluation").Rows(CurrentRow + 2)("Question")
txt4.Text = ds.Tables("evaluation").Rows(CurrentRow + 3)("Question")
txt5.Text = ds.Tables("evaluation").Rows(CurrentRow + 4)("Question")
Catch ex As Exception
End Try
every click to the next button my category and questions change.
every click i want also to save in my database
Private Sub Save_commit()
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
'get connection string declared in the Module1.vb and assing it to conn variable
con = New OleDbConnection(Get_Constring)
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
'I just use the textbox tag property to idetify if the data is new or existing.
sSQL = "INSERT INTO evaluationresult ([Com])" & _
" VALUES (?)"
cmd.CommandText = sSQL
cmd.Parameters.AddWithValue("#FacultyID", txtresult.Text)
'cmd.Parameters.AddWithValue("#IDNumber", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Com", OleDbType.Numeric).Value
' cmd.Parameters.AddWithValue("#Know", OleDbType.Numeric).Value
'cmd.Parameters.AddWithValue("#Teaching", OleDbType.Numeric).Value
'cmd.Parameters.Addwithvallue("#man", OleDbType.Numeric).Value()
'cmd.Parameters.AddWithValue("#ID", OleDbType.Numeric).Value
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ErrorToString)
Finally
con.Close()
End Try
End Sub
please improve