fill datagridview based on combobox selected item which depends on another selected combobox from database - vb.net

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)

Related

How to search data from textbox and fill specific columns of datagridview from SQL database?

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

add items from access to combobox vb.net

I want to fill a combobox with items from ms access database.
here's my code..
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ainunandile\Desktop\ElectionDB.mdb;Persist Security Info=False;")
conn.Open()
sqlQry = "SELECT * FROM Candidates where Position='President'"
cmd = New OleDbCommand(sqlQry, conn)
rdr = cmd.ExecuteReader
While rdr.Read()
ComboBox1.Items.Add(rdr("CandidateName").ToString())
End While
however the combobox won't fill up, but if i remove the "where Position ='President'" the code works, can someone help me i've been stuck here for hours.
you can try this i hope this work.
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ainunandile\Desktop\ElectionDB.mdb;Persist Security Info=False;")
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cn.Open()
Dim cm As New OleDbCommand("select * from Candidates where Position='President'", cn)
Dim dr As OleDbDataReader = cm.ExecuteReader
While dr.Read
ComboBox1.Items.Add(dr(1).ToString)
End While
dr.Close()
cn.Close()
End Sub

Syntax error in INSERT into statement when adding to access database

Someone please help me on finding the error on my code.
the error is at the line inside my try and catch where im trying to add record on my database Access. the error is "Syntax error in INSERT into statement". I already tried using
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
on my registration for voters and it works fine. idk why it doesnt work on this form (user registration).
Imports System.Data.OleDb
Public Class UserRegister
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String
Dim dbSource As String
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
Private Sub Label4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Label4.Click
End Sub
Private Sub UserRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dbProvider = " PROVIDER=Microsoft.jet.OLEDB.4.0;"
dbSource = "Data Source= C:\Users\Ronel\Documents\database\CSdatabase.mdb"
con.ConnectionString = dbProvider & dbSource
con.Open()
sql = "SELECT*FROM tblUsers"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Users")
MsgBox("Database now Open")
con.Close()
'MsgBox("Database now Close")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cb As New OleDb.OleDbCommandBuilder(da)
Dim dsNewRow As DataRow
Dim empty =
Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
MessageBox.Show(String.Format("PLEASE FILL ALL FIELDS:"))
Else
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("Username") = TextBoxUser.Text
dsNewRow.Item("Password") = TextBoxPass.Text
dsNewRow.Item("LastName") = TextBoxFN.Text
dsNewRow.Item("GivenName") = TextBoxGN.Text
dsNewRow.Item("MiddleName") = TextBoxMN.Text
' Try
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
' Catch ex As Exception
MsgBox("Error updating")
' End Try
' Me.Dispose()
'Comelec.Show()
End If
End Sub
End Class
I see a few problems. First, your SQL statement needs some spaces in it. Instead of sql = "SELECT*FROM tblUsers", use sql = "SELECT * FROM tblUsers".
Second, when using OleDbCommandBuilder, the code connects to the database using the SELECT statement you provided for the DataAdapter, and uses that to generate the necessary SQL for Update, Delete, and Insert statements. The connection to the database needs to be open for this to occur -- you connection is closed at the point where the CommandBuilder is running. This is probably where the syntax error is coming from.
The CommandBuilder will create these statements using all of the fields specified in the SELECT. If you have fields in your Users table other than the five you are attempting to populate, the OleDbCommandBuilder is still going to build an INSERT statement that will attempt to fill those fields as well. Depending on how your table is structured, this may cause rows to be rejected if required fields aren't populated. To take a look at what SQL statements are being generated, you can look at properties of the DataAdapter object after using the CommandBuilder:
con.Open
sql = "SELECT * FROM tblUsers"
da = New OleDb.OleDbDataAdapter(sql, con)
Dim cb As New OleDb.OleDbCommandBuilder(da)
Debug.Print("SELECT: " & da.SelectCommand.CommandText)
Debug.Print("UPDATE: " & da.UpdateCommand.CommandText)
Debug.Print("DELETE: " & da.DeleteCommand.CommandText)
Debug.Print("INSERT: " & da.InsertCommand.CommandText)
Some additional reading on CommandBuilders is available here: http://msdn.microsoft.com/en-us/library/tf579hcz%28v=vs.110%29.aspx
Give this a try:
Imports System.Data.OleDb
Public Class UserRegister
Const dbProvider As String = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
Dim dbSource As String = "Data Source=C:\Users\Ronel\Documents\database\CSdatabase.mdb"
Dim con As New OleDb.OleDbConnection(dbProvider & dbSource)
Dim ds As New DataSet
Dim da As New OleDb.OleDbDataAdapter
'Specify only the fields you need
Dim sql As String = "SELECT UserName, Password, LastName, GivenName, MiddleName FROM tblUsers"
Private Sub UserRegister_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
con.Open()
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "Users")
' Get commands now, while connection is open. Do this once when the form is loaded, not every time button is clicked.
Dim cb As New OleDb.OleDbCommandBuilder(da)
con.Close()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' Validation code goes here
If empty.Any Then
MessageBox.Show(String.Format("PLEASE FILL ALL FIELDS:"))
Else
Dim dsNewRow As DataRow
dsNewRow = ds.Tables("Users").NewRow()
dsNewRow.Item("Username") = TextBoxUser.Text
dsNewRow.Item("Password") = TextBoxPass.Text
dsNewRow.Item("LastName") = TextBoxFN.Text
dsNewRow.Item("GivenName") = TextBoxGN.Text
dsNewRow.Item("MiddleName") = TextBoxMN.Text
Try
con.Open()
ds.Tables("Users").Rows.Add(dsNewRow)
da.Update(ds, "Users")
Catch ex As Exception
MsgBox("Error updating: " & Err.Description)
Finally
con.Close()
End Try
End If
End Sub
End Class

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

Insert a record in sql database using vb.net datatable and datarow features

I am trying to insert a record in sql database using vb.net dataadapter, datatable, and datarow features. I use the following code but it gives me an error:
Object reference not set to an instance of an object
Imports System.Data.SqlClient
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=drpractice;Integrated Security=True")
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Try
cn.Open()
da.SelectCommand = New SqlCommand("SELECT * FROM [emp_tbl]", cn)
da.Fill(ds)
Dim dt As New DataTable
dt = ds.Tables("emp_tbl")
'Error in this line(Object reference not set to an instance of an object)'
Dim dr As DataRow = dt.NewRow()
dr.Item("emp_id") = TextBox1.Text.Trim
dr.Item("emp_name") = TextBox2.Text.Trim
dr.Item("salary") = TextBox3.Text.Trim
dr.Item("age") = TextBox4.Text.Trim
dr.Item("emp_group") = TextBox5.Text.Trim
dt.Rows.Add(dr)
da.Update(ds)
MsgBox("Record Successfully Inserted")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
check this out : Dim dr As DataRow = new dt.NewRow()
You have done everything good but change the following line:
da.Update(ds)
As following:
Dim ESCBuilder As SqlCommandBuilder = New SqlCommandBuilder(da)
ESCBuilder.GetUpdateCommand()
da.UpdateCommand = ESCBuilder.GetUpdateCommand()
da.Update(ds)
Based on the feedback here and elsewhere, the following code worked for me:
TestDataSet.GetChanges()
testTableAdapter.Fill(TestDataSet.log_test)
log_testDataGridView.Refresh()
What I needed to do was, create a new row, and go get the next value for the Primary Key(VARCHAR, NOT INT, because revisions got an "R" appended to the PK...not my rule...the rule of the company).
I wanted to put the refresh as close to the getting of the PK, which I had last after assigning values to the new datarow so it would get the latest Max +1.
So, I put the above code just before looking up the PK, and after assigning values to the datarow, other than PK. The code above caused the datarow to blank out. So, I put the above code just prior to the creation of the new DataRow.
For my code, this caused the code to get the latest data from the SQL table, then add the new datarow, and finally determine the last PK. Because the data used to populate the datarow is off my form, and there is no caclulations, the code runs fast enough for my needs. I suspect, if the connection to my database was slow, and/or, the number of people running the same process were substantial, I would have errors, such as duplicate PKs.
My answer to that would be to assign the datarow field values to variables, run the refresh, then assign the variables to the fields and save immediately.
Perhaps another way would be to get the new PK, then save an empty record, and then fill the record, except that enough of the fields in my table are REQUIRED so I might as well not try creating a blank record first.
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
‘ cmd = New SqlCommand("select * from Doctor", con)
str = "insert into Doctor values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "' )"
cmd = New SqlCommand(str, con)
count = cmd.ExecuteNonQuery()
MessageBox.Show(count & " Record inserted")
con.close()
End Sub
Imports System.Data.SqlClient
Public Class Form4
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim str As String
Dim count As Integer
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
con = New SqlConnection("server=SHREE-PC;database=Hospital;INTEGRATED SECURITY=SSPI;")
con.Open()
cmd = New SqlCommand("select * from Patient", con)
cmd = New SqlCommand("Delete from Patient where Name ='" & TextBox1.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Address='" & TextBox2.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Dieses='" & TextBox3.Text & "'", con)
cmd = New SqlCommand("Delete from Patient where Patient_no=" & TextBox4.Text & "", con)
‘you can take any row in your program
count = cmd.ExecuteNonQuery()
MessageBox.Show("Record Deleted")
End Sub