I've read existing code in stackoverflow but I'm still lost as how do I fix this.
This row already belongs to this table.
Any suggestions always is appreciated.
It errors out on my command button save event.
I've listed code for the entire form just to give you an idea on what I'm doing. Hope this helps
Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
DataGridView1.EndEdit()
Dim con As SqlConnection = CompDB.GetConnection
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim SPgetStandards As String = "dbo.SPgetStandards"
Dim SPgetRecordDetail As String = "dbo.SPgetRecordDetail"
Dim dsStandard As New DataSet
Dim dsRecords As New DataSet
Dim currentrow As DataRow
Dim currentcolumn As DataColumn
MsgBox("Record id is " & RecordID)
Using con
con.Open()
Dim Standardsdataadapter As New SqlClient.SqlDataAdapter(SPgetStandards, con)
Dim Detaildataadapter As New SqlClient.SqlDataAdapter(SPgetRecordDetail, con)
Detaildataadapter.Fill(dsRecords, "Record")
Standardsdataadapter.Fill(dsStandard, "Standard")
'5/31/13
'Figured out how to run a loop through a table and write to the console
For Each currentrow In dsStandard.Tables("Standard").Rows
For Each currentcolumn In dsStandard.Tables("Standard").Columns
'Debug.WriteLine(currentrow(currentcolumn) & ControlChars.Tab & ControlChars.Tab)
'MsgBox(currentcolumn.ToString)
'Debug.WriteLine(currentrow.Item(0))
Next currentcolumn
Next currentrow
' con.Close()
'con.Dispose()
Dim newrow As DataRow = dsRecords.Tables("Record").NewRow
For Each oRow As DataGridViewRow In DataGridView1.Rows
If Convert.ToInt16(oRow.Cells("chkbox").Value) = 1 Then
' Debug.WriteLine("It was clicked ", DataGridView1.Columns.Item(1))
Debug.WriteLine(oRow.Cells("ID").Value)
'dsStandard.Tables.Add.Rows("RecordID") = 1234
'dsRecords.Tables.Add.Rows("Standard_Name_ID") = 1234
' newrow("Record_Detail_ID") = RecordID
' newrow("Record_ID") = RecordID
newrow("Standard_Name_ID") = (oRow.Cells("ID").Value)
'/////Errors out here!!!!!dsRecords.Tables("Record").Rows.Add(newrow) '/////Errors out here!!!!!
dsRecords.AcceptChanges()
End If
Next
End Using
End Sub
Move this line:
Dim newrow As DataRow = dsRecords.Tables("Record").NewRow
To be the first line inside of your If block.
Related
Im having trouble getting the correct data to display in a DataGridView. I have two tables (Student) and (Module) in an access db, I have the text boxes displaying the data from the Student tables but i need the DataGridView to display their corresponding modules. the code is
Public Class frnMain
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = Students.accdb")
Dim objStudentDA As New OleDb.OleDbDataAdapter("Select * From Student", objConnection)
Dim objStudentCB As New OleDb.OleDbCommandBuilder(objStudentDA)
Dim objDataSet As New DataSet()
Dim objModuleDA As New OleDb.OleDbDataAdapter("Select * from Student", objConnection)
Dim objModuleCB As New OleDb.OleDbCommandBuilder(objModuleDA)
Dim Counter As Integer = 1
Private Sub frnMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Retrieve()
FillStudentDetails()
End Sub
Public Sub Retrieve()
objDataSet.Clear()
objStudentDA.FillSchema(objDataSet, SchemaType.Source, "Student")
objStudentDA.Fill(objDataSet, "student")
objModuleDA.FillSchema(objDataSet, SchemaType.Source, "Module")
objModuleDA.Fill(objDataSet, "Module")
'Set Relationships
objDataSet.Relations.Clear()
objDataSet.Relations.Add("student2Module", objDataSet.Tables("Student").Columns("StudentId"),
objDataSet.Tables("Module").Columns("StudentId"))
End Sub
Public Sub FillStudentDetails()
Dim objrow As DataRow
Dim objModule As DataRow
objrow = objDataSet.Tables("Student").Rows.Find(Counter)
objModule = objDataSet.Tables("Module").Rows.Find(Counter)
mtbStudentId.Text = objrow.Item("StudentId")
txtName.Text = objrow.Item("StudentName")
txtAddress.Text = objrow.Item("StudentAddress")
For Each objModules In objrow.GetChildRows("Student2Module")
dgvModule.DataSource = objDataSet.Tables(0)
Next
End Sub
I know the code is wrong in the for loop at the end I was just experimenting to see if i could get it. thanks in advance.
I fixed it by using fixed columns and just looping through the other table
dgvModule.ColumnCount = 3
dgvModule.Columns(0).Name = "Module ID"
dgvModule.Columns(1).Name = "Module Name"
dgvModule.Columns(2).Name = "Student Id "
dgvModule.Rows.Clear()
For i As Integer = 1 To objDataSet.Tables("Module").Rows.Count
objModule = objDataSet.Tables("Module").Rows.Find(i)
If currentId = objModule.Item("StudentId") Then
Dim row As String() = New String() {(objModule.Item("ModuleId")), objModule.Item("ModuleName"), objModule.Item("StudentId")}
dgvModule.Rows.Add(row)
Else
End If
Next
I am currently writing a simple stock control Visual Basic program linked to a database.
Here's what it looks like so far.
The form displays the data in a DataGrid View and I am trying to refresh my DataGridView automatically when data is changed (using SQL) in the database I am using.
After doing some research I have found that the best way to do this is by binding the data table (using BindingSource) to the DataGridView
However I am struggling to implement this, as every implementation I have tried results in a blank DataGridView and would thoroughly appreciate it if someone could assist me.
Here's the code:
Imports System.Data.OleDb
Public Class Form1
Public connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=dbStock.accdb"
Public conn As New OleDb.OleDbConnection(connectionString)
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TblStockControlTableAdapter.Fill(Me.DbStockDataSet.tblStockControl)
For i As Integer = 1 To 5
ComboBoxQty1.Items.Add(i)
ComboBoxQty2.Items.Add(i)
Next
Dim SqlQuery As String = "Select tblStockControl.[EggType] FROM tblStockControl"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
'DataGridView1.DataSource = dt
For Each row As DataRow In dt.Rows
ComboBoxAdd.Items.Add(row.Item(0))
Next
For Each row As DataRow In dt.Rows
ComboBoxTake.Items.Add(row.Item(0))
Next
End Sub
Private Sub btnAddEgg_Click(sender As Object, e As EventArgs) Handles btnAddEgg.Click
conn.Open()
Dim SqlQuery As String = "Select tblStockControl.[Quantity] FROM tblStockControl WHERE EggType = '" & ComboBoxAdd.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Dim qty As Integer = 0
For Each row As DataRow In dt.Rows
For Each column As DataColumn In dt.Columns
qty = row(column)
Next
Next
Dim NewQty As Integer = qty + CInt(ComboBoxQty2.Text)
UpdateAddQty(NewQty)
conn.Close()
End Sub
Function UpdateAddQty(ByRef NewQty As Integer) As Integer
Dim SqlUpdate As String = "UPDATE tblStockControl SET Quantity = '" & NewQty & "' WHERE EggType = '" & ComboBoxAdd.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Connection = conn
.ExecuteNonQuery()
End With
Return (Nothing)
End Function
Private Sub btnViewStock_Click(sender As Object, e As EventArgs) Handles btnViewStock.Click
'Add code to open Access file.
End Sub
Private Sub btnTakeEgg_Click(sender As Object, e As EventArgs) Handles btnTakeEgg.Click
conn.Open()
Dim SqlQuery As String = "Select tblStockControl.[Quantity] FROM tblStockControl WHERE EggType = '" & ComboBoxTake.Text & "'"
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Dim qty As Integer = 0
For Each row As DataRow In dt.Rows
For Each column As DataColumn In dt.Columns
qty = row(column)
Next
Next
Dim NewQty As Integer = CInt(ComboBoxQty1.Text) - qty
UpdateTakeQty(NewQty)
conn.Close()
End Sub
Function UpdateTakeQty(ByRef NewQty As Integer) As Integer
Dim SqlUpdate As String = "UPDATE tblStockControl SET Quantity = '" & NewQty & "' WHERE EggType = '" & ComboBoxTake.Text & "'"
Dim SqlCommand As New OleDbCommand
With SqlCommand
.CommandText = SqlUpdate
.Connection = conn
.ExecuteNonQuery()
End With
Return (Nothing)
End Function
End Class
If you are using a DataTable , then reset the dataasource of the DataGridView.I mean you need to read data from the database again. :
'Do this every time you add/Update a data
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "tblStockControl")
Dim dt As DataTable = ds.Tables("tblStockControl")
Or you can just create a row for every data you add to your database :
'Do this every time you add a data
DataGridViewRow row = (DataGridViewRow)DataGridView1.Rows[0].Clone()
row.Cells[0].Value = "Alex"
row.Cells[1].Value = "Jordan"
DataGridView1.Rows.Add(row)
I am coding a VB.NET program, which uses SQLite as a database.
My problem is when the form is loading it is displaying all values from a particular column (questions in my case) from the database to the ListBox. Then if the user clicks on any item (ListBox index change), the corresponding value from the database (answer) displays in a RichTextBox. This works as expected.
When the user types something in a TextBox and clicks the search Button, it is expected to show the questions from the database according to TextBox.Text as a tag column in the database to the same ListBox. This also works fine.
The problem begins when the ListBox index changes now. If the search result is only one item in the ListBox, the index will be zero and the RichTextBox shows the first item of the database insted of the corresponding value of the ListBox item.
My code is here:
Sub showData()'''this shows questions when form loads
connect()
Dim da As New SQLiteDataAdapter("select * from elect", connection)
'Dim dt As New DataTable
Dim ds As New DataSet
da.Fill(ds, "elect")
Dim mySelectQuery As String = "select * from elect"
Dim sqConnection As New SQLiteConnection(connection)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
'sqConnection.Open()
Try
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
' Always call Read before accessing data.
Do While sqReader.Read()
Dim sName = sqReader.Item("question")
ListBox1.Items.Add(sName)
Loop
' always call Close when done reading.
sqReader.Close()
' Close the connection when done with it.
Finally
connection.Close()
End Try
End Sub
Public Sub NavigateRecords()
page1.Clear()''page is rich text box
connect()
Dim da As New SQLiteDataAdapter("select * from elect", connection)
'Dim dt As New DataTable
Dim ds As New DataSet
da.Fill(ds, "elect")
Dim mySelectQuery As String
mySelectQuery = "select * from elect"
Dim sqConnection As New SQLiteConnection(connection)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
Dim num As Integer = Me.inc = Conversions.ToInteger(ListBox1.SelectedIndices.ToString)
MsgBox(num)
Me.inc = Conversions.ToInteger(ListBox1.SelectedIndex.ToString)
If (Me.inc > -1) Then
Dim ans As String = Conversions.ToString(ds.Tables.Item("elect").Rows.Item(Me.inc).Item(2))
page1.Text = (ans)
End If
End Sub
Private Sub search()
connect()
Dim da As New SQLiteDataAdapter("select * from elect", connection)
'Dim dt As New DataTable
Dim ds As New DataSet
da.Fill(ds, "elect")
Dim mySelectQuery As String = ("select * from elect WHERE tag like'%" & txtSearch.Text & "%' ")
Dim sqConnection As New SQLiteConnection(connection)
Dim sqCommand As New SQLiteCommand(mySelectQuery, sqConnection)
Try
Dim sqReader As SQLiteDataReader = sqCommand.ExecuteReader()
' Always call Read before accessing data.
Do While sqReader.Read()
Dim sName = sqReader.Item("question")
ListBox1.Items.Add(sName)
Loop
If ListBox1.Items.Count = 0 Then
MsgBox("Nothing Found ")
showData()
End If
' always call Close when done reading.
sqReader.Close()
' Close the connection when done with it.
Finally
connection.Close()
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
page1.Visible = True
ListBox1.Visible = False
Label1.Visible = False
NavigateRecords()
End Sub
i have follow code in my vb.net project
the connection to the sql db is fine & ok , only when i try to fill the listbox i get a error
Public Class Form1
Private myTable As New DataTable()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetSerialPortNames()
FillListBox()
'------------
myTable.Columns.Add("naam", GetType(String))
myTable.Columns.Add("waarde", GetType(Integer)) '<<<< change the type of this column to what you actually need instead of integer.
ListBox1.DisplayMember = "naam"
ListBox1.ValueMember = "waarde"
ListBox1.DataSource = myTable
End Sub
and
Private Sub FillListBox()
Dim naam As String
Dim stringConn As String
Dim stringCmd As String
Dim myConn As MySqlConnection
Dim myCmd As MySqlCommand
'Frame your query here.
stringCmd = "SELECT id,naam,voornaam FROM deelnemers WHERE finger = FALSE ORDER BY naam "
'Frame your connection string here.
stringConn = "********************************************"
'Get your connection here.
myConn = New MySqlConnection(stringConn)
'Get a command by using your connection and query.
myCmd = New MySqlCommand(stringCmd, myConn)
'Open the connection.
myConn.Open()
'create a reader to store the datum which will be returned from the DB
Dim myReader As MySqlDataReader
'Execute your query using .ExecuteReader()
myReader = myCmd.ExecuteReader()
'Reset your List box here.
ListBox2.Items.Clear()
While (myReader.Read())
'Add the items from db one by one into the list box.
naam = myReader.GetString(1) & " " & myReader.GetString(2)
'ListBox2.Items.Add((naam))
myTable.Rows.Add(naam, myReader.GetString(0))
End While
'Close the reader and the connection.
myReader.Close()
myConn.Close()
End Sub
i get error on follow line
myTable.Rows.Add(naam, myReader.GetString(0))
with follow description : Input array is longer than the number of columns in this table.
someone who see ??
I suspect that your myTable datatable does not have any columns...
Try changing:
While (myReader.Read())
'Add the items from db one by one into the list box.
naam = myReader.GetString(1) & " " & myReader.GetString(2)
'ListBox2.Items.Add((naam))
myTable.Rows.Add(naam, myReader.GetString(0))
End While
to this:
Dim row As DataRow
While (myReader.Read())
'Add the items from db one by one into the list box.
row = myTable.NewRow()
row("naam") = myReader.GetString(1) & " " & myReader.GetString(2)
row("waarde") = myReader.GetString(0)
myTable.Rows.Add(row)
End While
you should still get an error, but at least this way you'll know what columns are missing...
update
Also, change this:
FillListBox()
'------------
myTable.Columns.Add("naam", GetType(String))
myTable.Columns.Add("waarde", GetType(Integer)) '<<<< change the type of this column to what you actually need instead of integer.
to this:
'------------
myTable.Columns.Add("naam", GetType(String))
myTable.Columns.Add("waarde", GetType(Integer)) '<<<< change the type of this column to what you actually need instead of integer.
FillListBox()
Every single comment i have been reading said that this code works..
But when I try to type in text to the textbox no autocomplete appears and it just blinks.. please help,, i m new to winforms
Private Sub txsCusID_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txsCusID.TextChanged
Dim cmd As New SqlClient.SqlCommand("SELECT DISTINCT fname + ' ' + lname AS clist FROM tblclient WHERE id LIKE '%" + txsCusID.Text.ToString + "%'", sqlconstr)
Dim ds As New DataSet
Dim da As New SqlClient.SqlDataAdapter(cmd)
da.Fill(ds, "list")
Dim col As New AutoCompleteStringCollection
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count - 1
col.Add(ds.Tables(0).Rows(i)("clist").ToString())
Next
txsCusID.AutoCompleteSource = AutoCompleteSource.CustomSource
txsCusID.AutoCompleteCustomSource = col
txsCusID.AutoCompleteMode = AutoCompleteMode.Suggest
End Sub
Here give this a try... I would suggest setting your table up and then loop through while adding to your source...
Dim dtCustomerNames As DataTable
dtCustomerNames = ds.Tables(0)
For Each row As DataRow In dtCustomerNames.Rows
'You have to continue to add your data here...'
txsCusID.AutoCompleteCustomSource.Add((row.Item("clist").ToString))
Next
txsCusID.AutoCompleteMode = AutoCompleteMode.Suggest
txsCusID.AutoCompleteSource = AutoCompleteSource.CustomSource
Let me know how it works out for you...
Thanks!