Index out of range exception cannot find column - vb.net

Hello I have this problem in came upon when trying to do simple manual search in vb.net. It says System.IndexOutOfRangeException: 'Cannot find column 4.'
could anyone explain what this means i am quite new to coding and dont quite get what i could to do fix this. In the attached database i have only one table called customer with 4 columns custid, custfname, custlname and dob.
This is the code and the error occurs in the btnNext and Navigaterecords. The database was made in sqlite
Imports System.Data.SQLite
Public Class Form1
Dim inc As Integer
Dim MaxRows As Integer
Dim ConnectionString As String = "Data Source=dbRoomBookings.db"
Dim ds As New DataSet
Dim dt As New DataTable
Dim mSQL As String = "SELECT * FROM Customer"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(mSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(ds, "customer")
dt = ds.Tables(0)
MaxRows = ds.Tables("customer").Rows.Count
con.Close()
Dim msSQL As String = "SELECT * FROM customer;"
dgvSearchResults.DataSource = display(msSQL, "customer")
End Sub
Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(4)
cboYear.Text = ds.Tables("Customer").Rows(inc).Item(5)
Else
MsgBox("no more rows")
End If
End Sub
Sub navigaterecords()
txtCusId.Text = ds.Tables("customer").Rows(inc).Item(0)
txtFname.Text = ds.Tables("customer").Rows(inc).Item(1)
txtLname.Text = ds.Tables("customer").Rows(inc).Item(2)
cboDay.Text = ds.Tables("customer").Rows(inc).Item(3)
cboMonth.Text = ds.Tables("customer").Rows(inc).Item(4)
cboYear.Text = ds.Tables("customer").Rows(inc).Item(5)
txtDbo.Text = ds.Tables("customer").Rows(inc).Item(3) & "/" & ds.Tables("customer").Rows(inc).Item(4) & "/" & ds.Tables("customer").Rows(inc).Item(5)
End Sub
Private Sub BtnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
navigaterecords()
Else
MsgBox("no more rows")
End If
End Sub
Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
navigaterecords()
End If
End Sub
Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
navigaterecords()
Else
End If
End Sub
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim sSQL As String
Dim newds As New DataSet
Dim newdt As New DataTable
If txtSearchFname.Text <> "" Then
sSQL = "SELECT * FROM customer WHERE custfname LIKE'" & txtSearchFname.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customer")
newdt = newds.Tables(0)
dgvSearchResults.DataSource = newdt
con.Close()
ElseIf txtSearchId.Text <> "" Then
sSQL = "SELECT * FROM customer WHERE custid ='" & txtSearchId.Text & "'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSQL, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customer")
newdt = newds.Tables(0)
dgvSearchResults.DataSource = newdt
con.Close()
End If
End Sub
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim con2 As New SQLiteConnection
Dim da2 As New SQLiteDataAdapter
Dim dsql, qsql As String
Dim ds2 As New DataSet
Dim dt2 As DataTable
con2 = New SQLiteConnection(ConnectionString)
dsql = "DELETE FROM customer WHERE custid = " & txtSearchId.Text & ""
qsql = "SELECT * FROM customer"
Dim cmd As New SQLiteCommand(qsql, con2)
con2.Open()
da2.DeleteCommand = con2.CreateCommand
da2.DeleteCommand.CommandText = dsql
da2.DeleteCommand.ExecuteNonQuery()
MsgBox("Row(s) Deleted !! ")
Dim da3 As New SQLiteDataAdapter(cmd)
da3.Fill(ds2, "customer")
dt2 = ds2.Tables(0)
dgvSearchResults.DataSource = dt2
con2.Close()
End Sub
Private Sub BtnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim con3 As New SQLiteConnection
Dim da3 As New SQLiteDataAdapter
con3 = New SQLiteConnection(ConnectionString)
Dim usql As String = "UPDATE Customer SET custfname = '" & txtFname.Text & "'" & "WHERE custid =" & CInt(txtCusId.Text) & ""
con3.Open()
da3.UpdateCommand = con3.CreateCommand
da3.UpdateCommand.CommandText = usql
da3.UpdateCommand.ExecuteNonQuery()
MsgBox("Row Updated")
End Sub
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim isql As String = "INSERT INTO customer(custfname, custlname, dob) VALUES('" _
& txtFname.Text & "','" & txtLname.Text & "','" & cboYear.Text _
& "-" & cboMonth.Text & "-" & cboDay.Text & "');"
Dim msql As String = "SELECT * FROM customer"
add(isql)
'refresh the Data Grid
dgvSearchResults.DataSource = display(msql, "customer")
End Sub
End Class

Here is the specific documentation on IndexOutOfRangeException: https://learn.microsoft.com/en-us/dotnet/api/system.indexoutofrangeexception
For visibility, the definition is:
The exception that is thrown when an attempt is made to access an
element of an array or collection with an index that is outside its
bounds.
In your case, you are trying to get a value by passing the index of a column but the index you're passing is greater than the total number of columns.
Assuming that your table definition has the following columns: custfname, custlname, and dob, the following represents when the Exception would occur:
Get column 0, returns the value of custfname
Get column 1, returns the value of custlname
Get column 2, returns the value of dob
Get column 3, throws an IndexOutOfRangeException
The same thing would also happen if you tried to get a value at a negative index too.

You have a 4-column table which will have indexes from 0 to 3 only:
custid is column 0, custfname is column 1, custfname is column 2, and dob is column 3.
So any attempt to access ds.Tables("customer").Rows(inc).Item(4) (and (5), etc) will yield an Index out of range exception.
But you seem to know that the table only has 4 columns; why are you then attempting to access columns that you know don't exist? I'm a bit confused by that. If you're trying to split DOB into day/month/year, you'll have to manipulate the dob value from the DOB composite column, Item(3).

Related

VB Net - How to get cascading drop down list to select self insert row without error?

I have 4 dropdownlist in my web form that is cascading, the value of the 1st dropdownlist will affect the selection of the 2nd dropdownlist and so on.
Protected Sub line_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level1_ID As Integer = Convert.ToInt32(line.SelectedValue.ToString())
FillProcess(level1_ID)
End Sub
Protected Sub ddlprocess_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level2_ID As Integer = Convert.ToInt32(ddlprocess.SelectedValue.ToString())
FillEquipment(level2_ID)
End Sub
Protected Sub equipment_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level3_ID As Integer = Convert.ToInt32(equipment.SelectedValue.ToString())
FillStep(level3_ID)
End Sub
Private Sub FillLine() '1st dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level1_id, [LCODE1]+ ' | '+[LNAME1] as [LCODE1]" _
& " FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP]"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
line.DataSource = dt
line.DataTextField = "LCODE1"
line.DataValueField = "level1_id"
line.DataBind()
line.Items.Insert(0, "")
End If
End Sub
Private Sub FillProcess(ByVal level1_ID As Integer) '2nd dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level2_id, [LCODE2]+ ' | '+[LNAME2] as [LCODE2] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level1_id = #level1_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level1_id", SqlDbType.Int).Value = level1_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
ddlprocess.DataSource = dt
ddlprocess.DataTextField = "LCODE2"
ddlprocess.DataValueField = "level2_id"
ddlprocess.DataBind()
ddlprocess.Items.Insert(0, "")
End If
End Sub
Private Sub FillEquipment(ByVal level2_ID As Integer) '3rd dropdown
Dim dt As New DataTable
Dim strSql = "select distinct level3_id, [LCODE3]+ ' | '+[LNAME3] as [LCODE3] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level2_id = #level2_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level2_id", SqlDbType.Int).Value = level2_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
equipment.DataSource = dt
equipment.DataTextField = "LCODE3"
equipment.DataValueField = "level3_id"
equipment.DataBind()
equipment.Items.Insert(0, "")
End If
End Sub
Private Sub FillStep(ByVal level3_ID As Integer) '4th dropdown
Dim dt As New DataTable
Dim strSql = "select distinct [LCODE4]+ ' | '+[LNAME4] as [LCODE4] " _
& "FROM [SQLIOT].[dbo].[ZVIEW_MCM_LEVEL_LOOKUP] where level3_id = #level3_id"
Using conn As New SqlConnection(ConStr),
cmd As New SqlCommand(strSql, conn)
cmd.Parameters.Add("#level3_id", SqlDbType.Int).Value = level3_ID
conn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count > 0 Then
[step].DataSource = dt
[step].DataTextField = "LCODE4"
[step].DataBind()
[step].Items.Insert(0, "")
End If
End Sub
The reason I want a blank 1st row is so that when the form loads I want all dropdownlist to start off empty. During testing I thought to try selecting back to blank 1st row after selecting a value. This causes an error to occur at:
'Any one of the selectedindexchanged sub depending on which list I used
Protected Sub line_selectedindexchanged(ByVal sender As Object, ByVal e As EventArgs)
Dim level1_ID As Integer = Convert.ToInt32(line.SelectedValue.ToString()) '--> issue here
FillProcess(level1_ID)
End Sub
Error message being:
Input string was not in a correct format.
Anything I can do to fix this?

Primary Key Voilation error while Adding Rows in a table using datagrid RowsAdded Event

I am facing a primary key voilation error in the following code:
Private Sub ProductForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'BismillahDBDataSet.Product' table. You can move, or remove it, as needed.
Me.ProductTableAdapter.Fill(Me.BismillahDBDataSet.Product)
AddHandler ProductGrid.RowsAdded, AddressOf ProductGrid_RowsAdded
Dim ProductAdapter = New SqlDataAdapter("Select * from product", My.Settings.BismillahDBCN)
Dim ProductTable = New DataTable()
ProductAdapter.Fill(ProductTable)
ProductGrid.DataSource = ProductTable
End Sub
Private Sub ProductGrid_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs)
Dim RowID As Integer = ProductGrid.CurrentRow.Index
Dim ColID As Integer = ProductGrid.CurrentCell.ColumnIndex
Try
SQLText("insert into Product (ProductID, ProductName,UnitPrice,QtyInHand) values('" & ProductGrid.Item(0, RowID).Value & "','" & ProductGrid.Item(1, RowID).Value & "','" & ProductGrid.Item(2, RowID).Value & "','" & ProductGrid.Item(3, RowID).Value & "')")
Catch ex As Exception
Exit Sub
Finally
' Dim RowID As Integer = ProductGrid.CurrentRow.Index
' Dim ColID As Integer = ProductGrid.CurrentCell.ColumnIndex
Dim cn As New SqlConnection(My.Settings.BismillahDBCN)
cn.Open()
Dim cmd As New SqlCommand
cmd.Connection = cn
Dim rdr As SqlDataReader
cmd.CommandText = "Select * from Product where Productid=" & ProductGrid.Item(0, ColID).Value
rdr = cmd.ExecuteReader
rdr.Read() 'while rdr.Read()
If rdr.HasRows = True Then
MsgBox("Productid already exists!, Enter new ProductID")
'TxtInvoiceNo.Focus()
' Exit Sub
End If
End Try
End Sub
I also tried UserAddedRows event but as soon as i start typing in PRODUCTID column of the PRODUCTGRID (even 1 digit) it displays the voilation message
Please help

How to get count of records in a table?

Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then

vb.net Data Gridview REfresh

i am having some issues updating a table that i have in a VB.net Windows Forms in VS 2012
i have setup the database from a service Data base, it just need a small amount of data stored locally
what i am trying to do when i create a new user it update the data grid view
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BDate1.Format = DateTimePickerFormat.Custom
BDate1.CustomFormat = "MM/dd/yyyy"
If fname.Text <> "" And lname.Text <> "" Then
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
' cn1.Open()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
cmd.CommandText = "INSERT INTO StudentTB (FirstName,LastName,Birthday,Avatar,Gender,Grade) values('" & fname.Text & "', '" & lname.Text & "', '" & BDate1.Text & "', '" & AvtarNM.Text & "', '" & gen & "', '" & TxtGrade.Text & "')"
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
DataGridView1.DataSource = dt
' cmd.ExecuteNonQuery()
cn.Close()
fname.Text = ""
lname.Text = ""
the issue is that i can clear the table and reload it with button but it does not show the updated values with out closing the application then reopening it, i have tried a few thing and nothing seems to refresh the connection and or update the database. any help would help.
thanks
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'DataGridView1.DataSource = Nothing
Database1DataSet1.StudentTB.Clear()
' Database1DataSet1.refresh()
' Dim myda As String
' cmd.Dispose()
' cmd.Connection = cn
'Me.Database1DataSet1.Clear()
Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
' 'myda = New SqlDataAdapter(cmd)
End Sub
here is the full code
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlClient.SqlDataReader
Imports System.Windows.Forms
Public Class Student
Dim cn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Nate\documents\visual studio 2012\Projects\WindowsApplication9\WindowsApplication9\Database1.mdf;Integrated Security=True")
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
Private dataAdapter As New SqlDataAdapter()
Dim gen As String
Dim bs As New BindingSource
Dim dt As New DataTable
Private Sub Student_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database1DataSet1.avTable' table. You can move, or remove it, as needed.
Me.AvTableTableAdapter.Fill(Me.Database1DataSet1.avTable)
'TODO: This line of code loads data into the 'Database1DataSet1.StudentTB' table. You can move, or remove it, as needed.
Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
cmd.Connection = cn
Form1.Hide()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If AvTableBindingSource.Position + 1 < AvTableBindingSource.Count Then
AvTableBindingSource.MoveNext()
Button7.PerformClick()
' Otherwise, move back to the first item.
Else
AvTableBindingSource.MoveFirst()
Button7.PerformClick()
End If
' Force the form to repaint.
Me.Invalidate()
End Sub
Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
PictureBox1.Image = System.Drawing.Bitmap.FromFile(ID.Text)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BDate1.Format = DateTimePickerFormat.Custom
BDate1.CustomFormat = "MM/dd/yyyy"
If fname.Text <> "" And lname.Text <> "" Then
If Not cn.State = ConnectionState.Open Then
cn.Open()
End If
' cn1.Open()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
cmd.CommandText = "INSERT INTO StudentTB (FirstName,LastName,Birthday,Avatar,Gender,Grade) values('" & fname.Text & "', '" & lname.Text & "', '" & BDate1.Text & "', '" & AvtarNM.Text & "', '" & gen & "', '" & TxtGrade.Text & "')"
cmd.ExecuteNonQuery()
dt.Load(cmd.ExecuteReader())
bs.DataSource = dt
DataGridView1.DataSource = bs
cn.Close()
fname.Text = ""
lname.Text = ""
End If
End Sub
Private Sub genPCI()
If rb1.Checked Then
gen = rb1.Text.ToString
ElseIf rb2.Checked Then
gen = rb2.Text.ToString
End If
End Sub
Public Function ChangeFormat(ByVal dtm As DateTime, ByVal format As String) As String
Return dtm.ToString(format)
End Function
Private Sub Closestudent_Click(sender As Object, e As EventArgs) Handles Closestudent.Click
Form1.Show()
Me.Close()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bs.EndEdit()
dataAdapter.Update(dt)
DataGridView1.DataSource = dt
' dt.Load(Command.ExecuteReader())
'Database1DataSet1.Reset()
'DataGridView1.Columns.Clear()
' DataGridView1.DataSource = Nothing
' Me.StudentTBTableAdapter.Fill(Me.Database1DataSet1.StudentTB)
' StudentTBBindingSource.ResetBindings(True)
' Database1DataSet1.refresh()
' Dim myda As String
' cmd.Dispose()
' cmd.Connection = cn
' StudentTBBindingSource.ResetBindings(False)
'Database1DataSet1.StudentTB.Clear()
' 'myda = New SqlDataAdapter(cmd)
' DataGridView1.DataSource = Database1DataSet1.StudentTB
End Sub
End Class
You can try like this
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
bs.EndEdit()
dataadapter.Update(dt)
DataGridView1.DataSource = dt
End Sub
UPDATE
or you can use bindingdatasource and delare it on your form class
Dim bs As New BindingSource
and in datagridview .. in button1_click
Dim dt As New DataTable
dt.Load(cmd.ExecuteReader())
bs.DataSource = dt
DataGridView1.DataSource = bs
So, if updated then will show after button4_click
Datagridview1.datasource = nothing
Dataset.reset
dim cmd as new sqldataadapter
cmd = "SELECT * FROM YOUR_DATABSE", con
con.open
cmd.fill(Dataset)
datagridview1.datasource = dataset(0).defaultview
Add these code to you button insert
okay after a lot of playing around this seem to fix my issue http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx well all i can say it is working no idea why but it works.
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Me.DataGridView1.DataSource = Me.StudentTBBindingSource
GetData("select * from StudentTB")
End Sub
Private Sub GetData(ByVal selectCommand As String)
Try
' Specify a connection string. Replace the given value with a
' valid connection string for a Northwind SQL Server sample
' database accessible to your system.
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Nate\documents\visual studio 2012\Projects\WindowsApplication9\WindowsApplication9\Database1.mdf;Integrated Security=True"
' Create a new data adapter based on the specified query.
Me.dataAdapter = New SqlDataAdapter(selectCommand, connectionString)
' Create a command builder to generate SQL update, insert, and
' delete commands based on selectCommand. These are used to
' update the database.
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
' Populate a new data table and bind it to the BindingSource.
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.StudentTBBindingSource.DataSource = table
' Resize the DataGridView columns to fit the newly loaded content.
' Me.DataGridView1.AutoResizeColumns( _
' DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
Catch ex As SqlException
MessageBox.Show("To run this example, replace the value of the " + _
"connectionString variable with a connection string that is " + _
"valid for your system.")
End Try
End Sub
By Using ComboBox To Search
sql = " select * from english_language where lang=' " & ComboBox2.Text & " ' "
da = New OleDb.OleDbDataAdapter(sql, con)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
DataGridView1.Refresh()
Try this code to btnClear.
DataGridView.DataSource = 0
Press clear button. After that click the reload button that you coded.
I think it will reset and reload the data in data grid view.

VB: How to bind a DataTable to a DataGridView?

I know this is a basic question that has already been answered thousand times, but I can't make it work.
I am working in Visual Studio 2010 and have two forms in my Windows Application. In the first one (Main.vb), the user enters his inputs and the calculation takes place. In the second one (DataAnalysis.vb) the calculation results are displayed.
In Main.vb, I create the temp table that will contains all the intermediary calculation steps:
Dim tableTempJDL As DataTable = New DataTable("TempJDL")
Dim column As DataColumn
column = New DataColumn("ID", GetType(System.Int32))
tableTempJDL.Columns.Add(column)
column = New DataColumn("PthObjekt", GetType(System.Double))
tableTempJDL.Columns.Add(column)
'further columns are after created using the same method
Then, in DataAnalysis.vb, I try to display the DataTable tableTempJDL into the DataGridViewBerechnung:
Public bindingSourceBerechnung As New BindingSource()
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
But then I don't understand how to fill the DataGridView...
Simply, you can make your table as the datasource of bindingsource in following way:
Me.bindingSourceBerechnung .DataSource = tableTempJDL
Later on, you can bind above binding source in your datagridview in following way:
Me.DataGridViewBerechnung.DataSource = Me.bindingSourceBerechnung
Public Class Form1
Dim CON As New SqlConnection
Dim CMD As New SqlCommand
Dim dt As New DataTable
Public Sub DbConnect()
If CON.State = ConnectionState.Open Then DbClose()
CON.ConnectionString = "Data Source = yourservername;Initial Catalog=your database name;Integrated Security=True"
CON.Open()
End Sub
Public Sub DbClose()
CON.Close()
CON.Dispose()
End Sub
Public Sub enabletext()
TextBox1.Enabled = True
End Sub
Public Sub CLEARFEILDS()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
ComboBox1.SelectedIndex = 0
DataGridView2.Rows.Clear()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.Select()
TextBox4.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
'AUTOSEACH()
DbConnect()
Dim SELECTQUERY As String = "SELECT PROD_CODE FROM TBLPRODUCT"
Dim MYCOMMAND As New SqlCommand(SELECTQUERY, CON)
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
Prod_Code.Items.Clear()
While MYREADER.Read
Prod_Code.Items.Add(MYREADER("PROD_CODE"))
End While
DbClose()
End Sub
Public Function InvCodeGen(ByVal CurrCode As String) As String
Dim RightSix As String = Microsoft.VisualBasic.Right(Trim(CurrCode), 3)
Dim AddValue As Integer = Microsoft.VisualBasic.Val(RightSix) + 1
Dim RetValue As String
If Microsoft.VisualBasic.Len(AddValue.ToString) = 1 Then
RetValue = "00" + AddValue.ToString
ElseIf (Microsoft.VisualBasic.Len(AddValue.ToString) = 2) Then
RetValue = "000" + AddValue.ToString
Else
RetValue = AddValue.ToString
End If
Return RetValue
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
CreateNewCode()
TextBox1.Enabled = False
DataGridView1.Visible = False
TextBox5.Visible = False
ComboBox1.Visible = True
AddCustomer()
'GridView2Load(GetDataGridView2())
End Sub
Private Sub CreateNewCode()
Dim CurrCode As String = ""
'Dim NewCode As String = "INV"
Dim NewCode As Integer
Dim mySelectQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myCommand As New SqlClient.SqlCommand(mySelectQuery, CON)
myCommand.CommandType = CommandType.Text
Dim myReader As SqlClient.SqlDataReader
DbConnect()
myReader = myCommand.ExecuteReader()
Do While myReader.Read()
If IsDBNull(myReader("INVNO")) Then
myReader.Close()
Dim myNewYearQuery As String = "SELECT MAX(INV_NO) AS INVNO FROM TBLINV_HEADER"
Dim myNewYearCommand As New SqlClient.SqlCommand(myNewYearQuery, CON)
myNewYearCommand.CommandType = CommandType.Text
Dim myNewYearReader As SqlClient.SqlDataReader
myNewYearReader = myNewYearCommand.ExecuteReader()
Do While myNewYearReader.Read()
CurrCode = Trim(myNewYearReader("INVNO").ToString)
Loop
myNewYearReader.Close()
Exit Do
Else
CurrCode = Trim(myReader("INVNO").ToString)
myReader.Close()
Exit Do
End If
Loop
DbClose()
NewCode = Trim(InvCodeGen(CurrCode))
TextBox1.Text = CInt(NewCode)
End Sub
Private Sub AddCustomer()
Dim dsCusCode As New DataSet
dsCusCode.Reset()
ComboBox1.Items.Clear()
Dim myCusCodeQuery As String = "SELECT CUST_CODE as Custcode FROM TBLCUSTOMER"
Dim daCusCode As New SqlClient.SqlDataAdapter(myCusCodeQuery, CON)
DbConnect()
daCusCode.Fill(dsCusCode, "TBLCUSTOMER")
DbClose()
Dim x As Integer
For x = 0 To dsCusCode.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dsCusCode.Tables(0).Rows(x).Item("Custcode").ToString)
'TextBox3.Text = dsCusCode.Tables(0).Rows(x).Item("custname").ToString
Next
ComboBox1.SelectedIndex = -1
x = Nothing
myCusCodeQuery = Nothing
dsCusCode.Dispose()
daCusCode.Dispose()
dsCusCode = Nothing
dsCusCode = Nothing
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Code As String
Code = ComboBox1.Text
Dim dsCode As New DataSet
dsCode.Reset()
Dim myCodeQuery As String = "SELECT cust_name as custname, cust_add1 as custadd FROM TBLCUSTOMER where Cust_Code = '" & Code & "'"
Dim daCode As New SqlClient.SqlDataAdapter(myCodeQuery, CON)
DbConnect()
daCode.Fill(dsCode, "TBLCUSTOMER")
DbClose()
TextBox2.Text = dsCode.Tables(0).Rows(0).Item("custname").ToString
TextBox3.Text = dsCode.Tables(0).Rows(0).Item("custadd").ToString
myCodeQuery = Nothing
dsCode.Dispose()
daCode.Dispose()
dsCode = Nothing
dsCode = Nothing
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim MYQUERY As String = "SELECT PROD_DESC , PROD_PRICE FROM TBLPRODUCT WHERE PROD_CODE='" & DataGridView2.Rows(I).Cells(1).Value & "'"
Dim MYCOMMAND As New SqlCommand(MYQUERY, CON)
DbConnect()
Dim MYREADER As SqlClient.SqlDataReader
MYREADER = MYCOMMAND.ExecuteReader
If MYREADER.Read() Then
DataGridView2.Rows(I).Cells(2).Value = MYREADER("PROD_DESC")
DataGridView2.Rows(I).Cells(3).Value = MYREADER("PROD_PRICE")
End If
DbClose()
Next
End Sub
Private Sub DataGridView2_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView2.CellFormatting
DataGridView2.Rows(e.RowIndex).Cells(0).Value = CInt(e.RowIndex + 1)
End Sub
Private Sub DataGridView2_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellEndEdit
For I As Integer = 0 To DataGridView2.Rows.Count - 1
Dim QTY As Double = DataGridView2.Rows(I).Cells(4).Value
Dim PRICE As Double = DataGridView2.Rows(I).Cells(3).Value
Dim AMOUNT As Double = QTY * PRICE
DataGridView2.Rows(I).Cells(5).Value = AMOUNT
Next
' SUM OF AMOUNT TOTAL
Dim COLSUM As Decimal = 0
For Each ROW As DataGridViewRow In DataGridView2.Rows
If Not IsDBNull(ROW.Cells(5).Value) Then
COLSUM += ROW.Cells(5).Value
End If
Next
TextBox4.Text = COLSUM
End Sub
'SAVE
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
If MsgBox("Are you sure want to save this record?", vbYesNo + vbQuestion) = vbYes Then
updateinvheader()
updategridvalue()
CLEARFEILDS()
End If
End Sub
Private Sub updateinvheader()
Dim insertquery1 As String = "insert into TBLINV_HEADER(inv_no,inv_date,inv_cust) values(#inv_no,#inv_date,#inv_cust)"
Dim command As New SqlCommand(insertquery1, CON)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_date", DateTime.Now)
command.Parameters.AddWithValue("#inv_cust", ComboBox1.Text)
DbConnect()
command.ExecuteNonQuery()
DbClose()
End Sub
Private Sub updategridvalue()
Dim i As Integer
Dim insertquery2 As String = "insert into TBLINV_detail(inv_lno,inv_no,inv_prod,inv_qty,inv_Price) values(#inv_lno,#inv_no,#inv_prod,#inv_qty,#inv_Price)"
Dim command As New SqlCommand(insertquery2, CON)
For i = 0 To DataGridView2.RowCount - 1
If DataGridView2.Rows(i).Cells(1).Value = "" Then
GoTo 100
Else
command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).RowIndex + 1)
'command.Parameters.AddWithValue("#inv_lno", DataGridView2.Rows(i).Cells(0).)
command.Parameters.AddWithValue("#inv_no", TextBox1.Text)
command.Parameters.AddWithValue("#inv_prod", DataGridView2.Rows(i).Cells(1).Value)
command.Parameters.AddWithValue("#inv_qty", DataGridView2.Rows(i).Cells(4).Value)
command.Parameters.AddWithValue("#inv_Price", DataGridView2.Rows(i).Cells(3).Value)
End If
DbConnect()
command.ExecuteNonQuery()
DbClose()
100: command.Parameters.Clear()
Next
MsgBox("data saved successfuly")
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
DataGridView1.Visible = True
TextBox5.Visible = True
ComboBox1.Visible = False
DbConnect()
Dim MYQUERY As String = "Select * FROM TBLCUSTOMER" &
" INNER Join TBLINV_HEADER ON TBLINV_HEADER.INV_CUST = TBLCUSTOMER.CUST_CODE" &
" WHERE TBLINV_HEADER.INV_NO ='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim DA As New SqlDataAdapter
DA.SelectCommand = CMD
Dim DT As New DataTable
DA.Fill(DT)
If DT.Rows.Count > 0 Then
MsgBox(DT.Rows(0)(1).ToString())
'ComboBox1.Text = DT.Rows(0)(1).ToString()
ComboBox1.Visible = False
TextBox5.Text = DT.Rows(0)(1).ToString()
TextBox2.Text = DT.Rows(0)(2).ToString()
TextBox3.Text = DT.Rows(0)(3).ToString()
End If
DbClose()
DataGridView1.DataSource = GETPRODUCTDETAILS()
End Sub
Private Function GETPRODUCTDETAILS() As DataTable
Dim PRODUCTDET As New DataTable
DbConnect()
Dim MYQUERY As String = " SELECT TBLINV_DETAIL.INV_LNO, TBLINV_DETAIL.INV_PROD, TBLPRODUCT.PROD_DESC, TBLINV_DETAIL.INV_PRICE, TBLINV_DETAIL.INV_QTY, (TBLINV_DETAIL.INV_QTY*TBLINV_DETAIL.INV_PRICE) AS AMOUNT FROM TBLINV_DETAIL " &
" INNER JOIN TBLPRODUCT On TBLPRODUCT.PROD_CODE = TBLINV_DETAIL.INV_PROD " &
" WHERE TBLINV_DETAIL.INV_NO='" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(MYQUERY, CON)
Dim READER As SqlDataReader = CMD.ExecuteReader()
PRODUCTDET.Load(READER)
DbClose()
Return PRODUCTDET
End Function
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim DELETEQUERY As String = "DELETE FROM TBLINV_DETAIL WHERE TBLINV_DETAIL.INV_NO= '" & TextBox1.Text & "'"
Dim DELETEQUERY2 As String = "DELETE FROM TBLINV_HEADER WHERE TBLINV_HEADER.INV_NO= '" & TextBox1.Text & "'"
Dim CMD As New SqlCommand(DELETEQUERY, CON)
Dim CMD2 As New SqlCommand(DELETEQUERY2, CON)
DbConnect()
CMD.ExecuteNonQuery()
CMD2.ExecuteNonQuery()
DbClose()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
ComboBox1.DataSource = Nothing
DataGridView1.DataSource = Nothing
MsgBox("DATA DELETED SUCCESSFULLY")
End Sub
End Class