How to search data from textbox and fill specific columns of datagridview from SQL database? - vb.net

I am trying to search itemcode by typing in textbox and i want to get specific columns in same row from SQL database. I have made columns with headers in datagridview and i want that searched data in that specific datagridview columns. I have written code but it's not working. I do not know how to do this. I am new and trying to learn vb. Please give some suggestion.
This is my code:
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Using cn As New SqlConnection("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true")
Using cmd2 As New SqlCommand("select itemcode As 'Item Code', item,qty As Quantity, weight as Weight from stockdata Where itemcode = #itemcode;", cn)
cmd2.Parameters.AddWithValue("#itemcode", TextBox1.Text)
cn.Open()
Dim dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
DataGridView1.DataSource = dt
For Each row As DataGridViewRow In DataGridView1.Rows
cmd2.Parameters.Add("#item", SqlDbType.VarChar)
cmd2.Parameters.Add("#qty", SqlDbType.VarChar)
cmd2.Parameters.Add("#weight", SqlDbType.VarChar)
With cmd2
row.Cells(1).Value = .Parameters("#item").Value
row.Cells(2).Value = .Parameters("#qty").Value
row.Cells(2).Value = .Parameters("#weight").Value
End With
cmd2.ExecuteNonQuery()
Next
End Using
End Using
End Sub

I used a TextBox located outside the DataGridView to enter the item code to search for. I added a Button to do the search and retrieve the data to a DataReader.
The DataReader then loads the DataTable which is declared as a form level (class level variable). We want to use the same DataTable every time we search so the items will be added to the grid. With the Load method if the DataTable already contains rows, the incoming data from the data source is merged with the existing rows. The DataTable is then bound to the DataGridView. Each time the user enters an item code in the TextBox and clicks the Search Button a new row will be added to the grid.
To make nicer looking Column headers use as alias in your Select statement. The As clause following the databse column name is the alias and will show up in the DataGridView as a header. If you have a space in your alias it must be enclosed in single quotes.
Private dt As DataTable
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dt = New DataTable()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Using cn As New SqlConnection("server= PANKAJ\SQLEXPRESS; database = pankaj billing software; integrated security=true")
Using cmd2 As New SqlCommand("select itemcode As 'Item Code', item,qty As Quantity, weight as Weight from stockdata Where itemcode = #itemcode;", cn)
cmd2.Parameters.AddWithValue("#itemcode", txtItemCode.Text)
cn.Open()
Dim dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub
P.S. Very glad to see the use of parameters and Using blocks! :-)

I saw several things to check:
When you use a datasource, you don't need to loop through the rows of your reader.
Check the connection string (is "pankaj billing software" really the name of the database? They don't usually have spaces)
You want square brackets ([] or double quotes ") rather than single quotes (') for the column name in the SQL statement.
It's also best to avoid the AddWithValue() function in favor of calling Add() with the exact column type and length.
We don't see where dt is declared.
Put it all together (guessing at column name/length, and haven't changed the database name yet) and you get this:
Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
Dim sql = "select itemcode As [Item Code], item, qty As Quantity, weight as Weight from stockdata Where itemcode = #itemcode;"
Dim dt As New DataTable()
Using cn As New SqlConnection("server=PANKAJ\SQLEXPRESS;database=pankaj billing software;integrated security=true"), _
cmd2 As New SqlCommand(sql, cn)
cmd2.Parameters.Add("#itemcode", SqlDbType.NVarChar, 10).Value = TextBox1.Text
cn.Open()
Using dr As SqlDataReader = cmd2.ExecuteReader()
dt.Load(dr)
End Using
End Using
DataGridView1.DataSource = dt
End Sub
But the big thing is "Not working" in never enough information about your code. What did you actually see that was different than what you expected? If there was an error message, what did it say exactly?

This is my script code:
protected void search_click(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection(conn);
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand cmd = new SqlCommand("spSearchUser", sqlCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#SearchTerm", "username");
cmd.Parameters.AddWithValue("#Username", txtSearch.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
searchBind();
GridView1.Visible = true;
txtSearch.Text = "";
}
}
This is WebForm code:
<div>
<table>
<tr>
<td>Search</td>
<td>
<asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" runat="server" Text="Go" onclick="search_click" />
</td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
</div>
This is my Store Procedure:
alter procedure spSearchUser
(
#SearchTerm nvarchar(50),
#Username nvarchar(50)
)
as
begin
set nocount on;
if #SearchTerm = 'username'
begin
select Username,City,Gender,Email from tblRegistration where Username
LIKE '%' + #Username + '%'
end
end

How about this?
'"C:\your_path\Northwind.mdb"
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports System.Windows.Forms
Public Class Form1
Inherits System.Windows.Forms.Form
Private bindingSource1 As New BindingSource()
Private dataAdapter As New OleDbDataAdapter()
<STAThreadAttribute()> _
Public Shared Sub Main()
Application.Run(New Form1())
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\your_path\Northwind.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
selectCommand = "Select * From MyExcelTable ORDER BY ID"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, btnUpdate.Click
Dim table As New DataTable()
Me.bindingSource1 = Me.DataGridView1.DataSource
table = Me.bindingSource1.DataSource
Me.dataAdapter.Update(table)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click, btnClose.Click
Me.Close()
End Sub
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\your_path\Northwind.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '%" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub
End Class

Related

fill datagridview based on combobox selected item which depends on another selected combobox from database

I am creating an add student windows form and it contains two comboboxes. the first one contains semester of the student and the second one contains the course code based on the value of semester. the problem I'm facing is that i also have a datagridview and i want to populate it with data of students contained in table of course code and as soon as i click semester combobox value of course code combobox changes, as soon as it changes, I want to load data of datagridview but it shows the error which basically is cannot convert datarows to string but when I use ComboBox1.ValueMember and load datagridview on clicking button it works fine. but when i load datagridview on combobox change it shows error.
this code works fine
Imports System.Data.OleDb
Public Class AddStudent
Dim con As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\Students.accdb")
Dim con1 As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source = C:\Users\Users.accdb")
Private Sub AddStudent_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.Open()
Dim cmd As New OleDbCommand("Select stud_roll From " + ComboBox1.SelectedValue + " where stud_roll = #roll1", con)
cmd.Parameters.AddWithValue("roll1", TextBox2.Text)
Dim myreader As OleDbDataReader = cmd.ExecuteReader
If myreader.Read() Then
con.Close()
MessageBox.Show("Student Inserted before")
Else
con.Close()
Dim cmd1 As New OleDbCommand("Insert into " + ComboBox1.SelectedValue + "(stud_roll,stud_name,date_of_birth,course,gender,mobile_no,semester) Values(#roll,#name,#dob,#course,#gender,#mobile,#semester)", con)
cmd1.Parameters.AddWithValue("roll", Convert.ToInt32(TextBox2.Text))
cmd1.Parameters.AddWithValue("name", TextBox1.Text)
cmd1.Parameters.AddWithValue("dob", DateTimePicker1.Value.Date)
cmd1.Parameters.AddWithValue("course", ComboBox1.SelectedValue)
cmd1.Parameters.AddWithValue("gender", ComboBox2.SelectedItem)
cmd1.Parameters.AddWithValue("mobile_no", MaskedTextBox1.Text)
cmd1.Parameters.AddWithValue("semester", Convert.ToInt32(ComboBox3.SelectedItem))
con.Open()
cmd1.ExecuteNonQuery()
con.Close()
MessageBox.Show("Records inserted successfully")
End If
con.Open()
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From " + ComboBox1.SelectedValue + "", con)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd3
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub
Private Sub Label8_Click(sender As Object, e As EventArgs) Handles Label8.Click
AddTeacher.Show()
End Sub
Private Sub ComboBox3_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox3.SelectedIndexChanged
con1.Open()
Dim cmd As New OleDbCommand("Select course_code From courses Where semester= " + ComboBox3.SelectedItem + "", con1)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
ComboBox1.DataSource = dt
ComboBox1.DisplayMember = "course_code"
ComboBox1.ValueMember = "course_code"
con1.Close()
End Sub
Private Sub Label14_Click(sender As Object, e As EventArgs) Handles Label14.Click
Courses.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
End Sub
End Class
when i load after combobox change like this, it shows error :- System.InvalidCastException: 'Operator '+' is not defined for string "Select stud_name, stud_roll From" and type 'DataRowView'.'
which is because of datarowview type conversion
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
con.Open()
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From " + ComboBox1.SelectedValue + "", con)
Dim da As New OleDbDataAdapter
da.SelectCommand = cmd3
Dim dt As New DataTable
dt.Clear()
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
End Sub
please help me with this.
1. Make sure to give the controls meaningful names: it will make your life easier. "ComboBox1" is not a meaningful name ;)
2. Don't create a single instance of a database connection that is re-used: you are meant to create the connection object, use it, and then dispose of it. There are mechanisms behind the scenes to make this efficient (Connection Pooling). There is an example of how to do it in a previous answer of mine.
3. You don't need to open and close the connection for da.Fill(dt): it does it automatically.
4. Because ComboBox1.SelectedValue comes from a datatable, you will need to extract the column of that datarowview, something like:
Dim tableName = DirectCast(ComboBox1.SelectedItem, DataRowView).Row.Field(Of String)("course_code")
Dim cmd3 As New OleDbCommand("Select stud_roll, stud_name, date_of_birth, course, gender,mobile_no, semester From [" & tableName & "]", con)

How to populate datagridview with dataset from select query?

I'm making a search bar using SELECT query and I want to transfer the results to a DataGridView. But I always get an empty DataGridView.
Nothing is wrong with the query, I already tried to input it manually in access. What am I doing wrong in the code? Here it is:
Using conn = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Dim da As New OleDbDataAdapter(Sql, conn)
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using
The issue is as I stated in the comment. ADO.Net uses the % for the like to maintain consistency with most major Sql engines. But I would like to point out that your query is unsafe and subject to SQL injection so I have included an example of your code using a parameter to pass user input to the command.
Also note that the OleDbDataAdapter can be declared in a Using statement the same way you did with the OleDbConnection Note that you may however have to widen the scope of the dataset (ds) if you plan on doing other things with it.
Using conn As OleDbConnection = New OleDbConnection(connstring)
Try
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE #Product"
Using da As OleDbDataAdapter = New OleDbDataAdapter(Sql, conn)
da.SelectCommand.Parameters.Add("#Product", OleDbType.Varchar).Value = txtSearchProduct.Text & "%"
Dim ds As New DataSet
da.Fill(ds)
DataGridView2.DataSource = ds.Tables(0)
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
End Using
Like Charles has mentioned its always better to use parameters. My answer is a bit different whereas it uses a reader and not an adapter, and a datatable and not an entire dataset. An adapter should only be used if you intend to write back to the table, or typical scenarios include binding procedures. A DataSet is typically used when you have multiple tables and have a need to relate them. Also note, you most likely want a preceding % in your parameter if you want to match the string regardless of the position in the search column.
Try
Using conn = New OleDbConnection("YourConnString")
conn.Open()
Dim Cmd As New OleDbCommand("SELECT * FROM Products WHERE [Product Name] LIKE #Product", conn)
Cmd.Parameters.AddWithValue("#Product", "'%" & txtSearchProduct.Text & "%'")
Dim ProductsRDR As OleDbDataReader = Cmd.ExecuteReader
Dim DTable As New DataTable With {.TableName = "Products"}
DTable.Load(ProductsRDR)
DataGridView1.DataSource = DTable
conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.ToString, MsgBoxStyle.OkOnly Or MsgBoxStyle.Exclamation, "Error")
End Try
All you have to do is replacing the * sign with % in your Sql string, just like this:
This is your wrong Sql string:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "*'"
Change it to this:
Dim Sql As String = "SELECT * FROM Products WHERE [Product Name] LIKE '" & txtSearchProduct.Text & "%'"
This should cover most of the common scenarios out there.
Imports System.Data.SqlClient
Public Class Form1
Dim sCommand As SqlCommand
Dim sAdapter As SqlDataAdapter
Dim sBuilder As SqlCommandBuilder
Dim sDs As DataSet
Dim sTable As DataTable
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
Dim connectionString As String = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"
Dim sql As String = "SELECT * FROM Stores"
Dim connection As New SqlConnection(connectionString)
connection.Open()
sCommand = New SqlCommand(sql, connection)
sAdapter = New SqlDataAdapter(sCommand)
sBuilder = New SqlCommandBuilder(sAdapter)
sDs = New DataSet()
sAdapter.Fill(sDs, "Stores")
sTable = sDs.Tables("Stores")
connection.Close()
DataGridView1.DataSource = sDs.Tables("Stores")
DataGridView1.ReadOnly = True
save_btn.Enabled = False
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
DataGridView1.[ReadOnly] = False
save_btn.Enabled = True
new_btn.Enabled = False
delete_btn.Enabled = False
End Sub
Private Sub delete_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles delete_btn.Click
If MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) = DialogResult.Yes Then
DataGridView1.Rows.RemoveAt(DataGridView1.SelectedRows(0).Index)
sAdapter.Update(sTable)
End If
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
sAdapter.Update(sTable)
DataGridView1.[ReadOnly] = True
save_btn.Enabled = False
new_btn.Enabled = True
delete_btn.Enabled = True
End Sub
End Class

How to Edit Datagrid Records and also in database

this is my code for loading the data from database to datagrid
Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim connString As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Database3.Accdb;"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [userinfo] ORDER BY ID", MyConn)
da.Fill(ds, "userinfo") 'Change items to your database name
Dim cb = New OleDbCommandBuilder(da)
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
If RequiredEntry() = True Then
Return
End If
Try
Dim cn As New OleDbConnection("Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Database3.Accdb;")
If cn.State = ConnectionState.Closed Then cn.Open()
Dim sSQL As String = "insert into [userinfo]([username],[password],[FirstName],[LastName],[Account]) values(#username,#password,#FirstName,#LastName,#Account)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
' UserName
If txtPassword.Text = txtConfirm.Text Then
Dim username As OleDbParameter = New OleDbParameter("#username", OleDbType.VarWChar, 50)
username.Value = txtUser.Text.ToString()
cmd.Parameters.Add(username)
Else
MsgBox("Password not matched")
End If
'password
Dim password As OleDbParameter = New OleDbParameter("#password", OleDbType.VarWChar, 50)
password.Value = txtPassword.Text.ToString()
cmd.Parameters.Add(password)
'First Name
Dim FirstName As OleDbParameter = New OleDbParameter("#FirstName", OleDbType.VarWChar, 50)
FirstName.Value = txtFirstName.Text.ToString()
cmd.Parameters.Add(FirstName)
' Last Name
Dim LastName As OleDbParameter = New OleDbParameter("#LastName", OleDbType.VarWChar, 50)
LastName.Value = txtLastName.Text.ToString()
cmd.Parameters.Add(LastName)
'Account
Dim Account As OleDbParameter = New OleDbParameter("#Account", OleDbType.VarWChar, 50)
Account.Value = cboAccount.GetItemText(cboAccount.SelectedItem)
cmd.Parameters.Add(Account)
If cmd.ExecuteNonQuery() Then
cn.Close()
MessageBox.Show("New User is Added successfully.", "Record Saved")
Call clear()
Me.Hide()
FileMaintenance.Show()
Else
MsgBox("New User Addition Failed ", MsgBoxStyle.Critical, "Addition Failed")
Return
End If
Catch ex As Exception
Exit Sub
End Try
End Sub
Private Sub NewUser_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
e.SuppressKeyPress = e.Control
If e.KeyCode = Keys.Enter Then
SendKeys.Send("{tab}")
End If
End Sub
and this is my for delete
Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
Dim connString As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\BackUp\Database3.Accdb;"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Dim rows As String
Try
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = (ds.Tables)
rows = DataGridView1.SelectedRows(0).Cells(0).Value.ToString()
da = New OleDbDataAdapter("Delete * from [userinfo] where ID=" & rows, MyConn)
da.Fill(ds, "userinfo")
Records_Load(sender, e)
Catch ex As Exception
MessageBox.Show("cannot delete empty records")
End Try
how can i edit my data from datagrid view as well in my database
also how can i lock the datagrid from entering fields accidentally
Your code is very wrong. You're retrieving the data correctly in the first place but then you're inserting and deleting incorrectly.
The idea is that you use one data adapter for all four operations, i.e. select, insert, update and delete. That's why it has SelectCommand, InsertCommand, UpdateCommand and DeleteCommand properties. You call Fill and it executes the SQL in the SelectCommand to retrieve data into a DataTable. You are then supposed to make all the changes you want, i.e. insert, update and delete, to the data in that DataTable. When you're done, you call Update on the data adapter and it will execute the SQL in the InsertCommand, UpdateCommand and DeleteCommand as required to save all the changes back to the database. Here's an example I wrote a long time ago:
Private connection As New SqlConnection("connection string here")
Private adapter As New SqlDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem", _
connection)
Private table As New DataTable
Private Sub InitialiseDataAdapter()
Dim delete As New SqlCommand("DELETE FROM StockItem WHERE ID = #ID", Me.connection)
Dim insert As New SqlCommand("INSERT INTO StockItem (Name, Quantity, Unit) VALUES (#Name, #Quantity, #Unit)", Me.connection)
Dim update As New SqlCommand("UPDATE StockItem SET Name = #Name, Quantity = #Quantity, Unit = #Unit WHERE ID = #ID", Me.connection)
delete.Parameters.Add("#ID", SqlDbType.Int, 4, "ID")
insert.Parameters.Add("#Name", SqlDbType.VarChar, 100, "Name")
insert.Parameters.Add("#Quantity", SqlDbType.Float, 8, "Quantity")
insert.Parameters.Add("#Unit", SqlDbType.VarChar, 10, "Unit")
update.Parameters.Add("#Name", SqlDbType.VarChar, 100, "Name")
update.Parameters.Add("#Quantity", SqlDbType.Float, 8, "Quantity")
update.Parameters.Add("#Unit", SqlDbType.VarChar, 10, "Unit")
update.Parameters.Add("#ID", SqlDbType.Int, 4, "ID")
Me.adapter.DeleteCommand = delete
Me.adapter.InsertCommand = insert
Me.adapter.UpdateCommand = update
Me.adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
End Sub
Private Sub GetData()
'Retrieve the data.
Me.adapter.Fill(Me.table)
'The table can be used here to display and edit the data.
'That will most likely involve data-binding but that is not a data access issue.
End Sub
Private Sub SaveData()
'Save the changes.
Me.adapter.Update(Me.table)
End Sub
Note that this example was written for SQL Server but you simply swap out all the SqlClient types for OleDb types and it works for Access.
If you want to save changes immediately for some reason then you simply call Update after each change.
By the way, your connection string should be written like this:
Dim connString As String = "Provider=Microsoft.Ace.Oledb.12.0; Data Source=|DataDirectory|\BackUp\Database3.Accdb;"

VB.Net OleDBConnection code to update access database from DataGridView

I have a simple userform with a DataGridView and I would like to use OleDB code to update the accdb database based on any entries made in the gridview. The load button works fine, but the save button produces this error:
Update requires a valid UpdateCommand when passed DataRow collection with modified rows.
Here is my code:
Imports System.Data.OleDb
Public Class Form1
Dim myConString As String
Dim con As OleDbConnection = New OleDbConnection
Dim Dadapter As OleDbDataAdapter
Dim DSet As DataSet
Dim DSet2 As DataSet
Dim ConCMD As OleDb.OleDbCommand
Private Sub load_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles load_btn.Click
myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\Psmccsfs01\snd\PRODUCTION\Licensed\Reporting\FTO Adjustment Tools\FTO_Log_DB.accdb;"
con.ConnectionString = myConString
con.Open()
Dadapter = New OleDbDataAdapter("select * from FTO_Log", con)
DSet = New DataSet
Dadapter.Fill(DSet, "FTO_Log")
DataGridView1.DataSource = DSet.Tables("FTO_Log")
con.Close()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Using con = New OleDbConnection(myConString)
con.Open()
Dadapter.Update(DSet, "FTO_Log")
End Using
End Sub
End Class
dataAdpater.UpdateCommand = new SqlCommand(
"UPDATE Categories SET CategoryName = #CategoryName " +
"WHERE CategoryID = #CategoryID", connection);
notice the typo in the code above, straight from the msdn site ;p
short and simple: http://msdn.microsoft.com/en-us/library/33y2221y%28v=vs.110%29.aspx

Displaying Data from SQL in TextBox by clicking ComboBox item in Visual Basic 2012

I have three columns in SQL, which I want the data displayed in three textboxes by clicking an item in ComboBox.
The issue is not really displaying. I can save the data fine and display. However, one of the text fields will only show one cell and not update when a different item is selected. Hope this is making sense.
Here is the code I have for saving:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myconnect As New SqlClient.SqlConnection
myconnect.ConnectionString = "Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True"
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
mycommand.Connection = myconnect
mycommand.CommandText = "INSERT INTO MyDiary (Title, DiaryContent, DiaryDate) VALUES (#Title, #DiaryContent, #DiaryDate)"
myconnect.Open()
Try
mycommand.Parameters.Add("#Title", SqlDbType.VarChar).Value = TextBox1.Text
mycommand.Parameters.Add("#DiaryContent", SqlDbType.VarChar).Value = TextBox2.Text
mycommand.Parameters.Add("#DiaryDate", SqlDbType.VarChar).Value = TextBox3.Text
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
And here is the code for displaying in form1:
Imports System.Data.SqlClient
Public Class Form1
Dim con As New SqlConnection
Dim ds As New DataSet
Dim da As New SqlDataAdapter
Dim sql As String
Dim inc As Integer
Dim MaxRows As Integer
Dim max As String
Dim dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'RioDiaryDataSet5.MyDiary' table. You can move, or remove it, as needed.
Me.MyDiaryTableAdapter.Fill(Me.RioDiaryDataSet5.MyDiary)
Dim con As New SqlConnection(" Data Source=.\INFLOWSQL;Initial Catalog=RioDiary;Integrated Security=True")
Dim cmd As New SqlCommand("Select Title,DiaryContent,DiaryDate FROM MyDiary ")
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
cmd.Connection = con
da.Fill(ds, "MyDiary")
con.Open()
ComboBox1.DataSource = ds.Tables(0)
ComboBox1.DisplayMember = "Title'"
ComboBox1.ValueMember = "DiaryContent"
End Sub
Private Sub NewEntryToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewEntryToolStripMenuItem.Click
AddEntry.Show()
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
If (Not Me.ComboBox1.SelectedValue Is Nothing) Then
Me.TextBox2.Text = ComboBox1.Text
Me.TextBox3.Text = ComboBox1.SelectedValue.ToString
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("DiaryDate").ToString() 'Where ColumnName is the Field from the DB that you want to display
End If
End Sub
End Class
As you can see from the code, I want to display Title and DiaryContent in two separate textboxes by clicking on Title in the Combobox. This works fine.
The issue I have is DiaryDate only shows the first entry and does not update when selecting the Item from ComboBox.
Can anyone help?
You can try to play with ComboBox's SelectedItem property. Since ComboBox's DataSource is DataTable here, SelectedItem of ComboBox represent a row in DataTable. Given DataRow in hand, you can display value of any column of DataRow in TextBoxes :
........
If (Not Me.ComboBox1.SelectedItem Is Nothing) Then
Dim SelectedItem = TryCast(comboBox1.SelectedItem, DataRowView)
Me.TextBox1.Text = SelectedItem.Row("Title").ToString()
Me.TextBox2.Text = SelectedItem.Row("DiaryContent").ToString()
Me.TextBox3.Text = SelectedItem.Row("DiaryDate").ToString()
End If
........
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from Register"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
Dim id = reader.Item("cid")
ComboBox1.Items.Add(id)
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim cn As New SqlClient.SqlConnection("Data Source=thee-pc;Initial Catalog=jobportal;Integrated Security=True")
Dim cmd As New SqlClient.SqlCommand
Dim tbl As New DataTable
Dim da As New SqlClient.SqlDataAdapter
Dim reader As SqlClient.SqlDataReader
Try
cn.Open()
Dim sql As String
sql = "select * from register where cid ='" + ComboBox1.Text + "'"
cmd = New SqlClient.SqlCommand(sql, cn)
reader = cmd.ExecuteReader
While reader.Read
TextBox1.Text = reader.Item("cname")
TextBox2.Text = reader.Item("dob")
End While
cn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub