VB Auto populate datagridview from datatable - vb.net

Is it possible to have a datagrieview populate directly from a datable ? Below is what I am trying in the form load. Basically I want it to show all the columns this query returns automatically
Dim con As New OleDbConnection
con = New OleDbConnection(connStr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim titleSQLStr As String = "SELECT * FROM Titles ORDER BY YearPublished DESC"
daYears = New OleDbDataAdapter(titleSQLStr, connStr)
daYears.Fill(dtYears)
cboYearsFillBy.DataSource = dtYears
cboYearsFillBy.DisplayMember = "YearPublished"
cboYearsFillBy.ValueMember = "YearPublished"
DataGridView1.AutoGenerateColumns = True
DataGridView1.DataSource = daYears
con.Close()

Change it to:
DataGridView1.DataSource = dtYears

Related

How to check if data already exists on listview from database

How to check if data already exists on listview from database?
Private Sub retrieve()
Dim imglist As New ImageList
imglist.ColorDepth = ColorDepth.Depth32Bit
ListView1.LargeImageList = imglist
ListView1.LargeImageList.ImageSize = New System.Drawing.Size(200, 200)
con.Close()
If con.State = ConnectionState.Closed Then con.Open()
Dim strsql As String = "SELECT dbo.pictures.Nu_pic, dbo.FilePictures.Num_File, dbo.FilePictures.Num_pic, dbo.pictures.pic,dbo.Files.Num_file FROM dbo.FilePictures INNER JOIN dbo.Files ON dbo.FilePictures.Num_File = dbo.Files.No_Genfile INNER JOIN dbo.pictures ON dbo.FilePictures.Num_pic = dbo.pictures.Nu_pic where dbo.Files.Num_file=" & Text_NoFile.Text
Dim dt_images As New DataTable
cmd.Connection = con
cmd.CommandText = strsql
adp.SelectCommand = cmd
adp.Fill(ds)
For Each dr As DataRow In ds.Tables(0).Rows
Dim imb_buffer = CType(dr("pic"), Byte())
Dim img_stream As New IO.MemoryStream(imb_buffer, True)
img_stream.Write(imb_buffer, 0, imb_buffer.Length)
imglist.Images.Add(dr("Nu_pic").ToString(), New Bitmap(img_stream))
img_stream.Close()
Dim lsvparent As New ListViewItem
'lsvparent.Text = dr("pic").ToString
lsvparent.ImageKey = dr("Nu_pic").ToString
ListView1.Items.Add(lsvparent)
lsvparent.Text = imglist.Images.Count.ToString
Next
con.Close()
End Sub
You can try one of two following ways:
Use select distinct .... in the SQL statement.
Check the existence of row by key before adding listview.

How to add dynamic Data in to the datagridviewcombobox column?

I am Developing VB.net application.
In that application I take DataGirdView to display data.
I took DataSource property of the datagridview to display 3 columns' data directly from database.
After those columns I add another DataGridViewComboBoxColumn. Then I a want to add dynamic the data into that ComboBoxColumn.
how to do this?
Private Function CreatComboBoxWithEnum() As DataGridViewComboBoxColumn
Dim combo As New DataGridViewComboBoxColumn()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Dim adpter As New SqlDataAdapter
Dim ds As New DataTable
Try
Sqlconn.Open()
Dim Query As String
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr ='" & val & "' "
COMMAND = New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = COMMAND
adpter.Fill(ds)
combo.DataSource = ds
combo.DataPropertyName = "OperationNo"
combo.Name = "OperationNo"
OperationNo.ValueMember = "OperationNo"
OperationNo.DisplayMember = "OperationNo"
Next
Sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Return combo
End Function
Private Sub load_operationNo()
Sqlconn = New SqlConnection
Sqlconn.ConnectionString = "server=.\SQLEXPRESS_2005;Initial Catalog=MachineShopScheduling ;Integrated Security=SSPI;"
Try
op.Name = "OperationNo"
DataGridView1.Columns.Add(op)
Sqlconn.Open()
Dim Query As String
Dim i As Integer = 0
For Each dr As DataGridViewRow In DataGridView1.Rows
Dim OPno As New DataGridViewComboBoxCell
With OPno
Dim adpter As New SqlDataAdapter
Dim dt As New DataTable
Dim val As String = dr.Cells("SrDataGridViewTextBoxColumn").Value.ToString
Query = "select OperationNo from RoutingCalculation where Sr = " & val & " order by sr"
Using cmd As New SqlCommand(Query, Sqlconn)
adpter.SelectCommand = cmd
adpter.Fill(dt)
End Using
.DataSource = dt
.ValueMember = "OperationNo"
.DisplayMember = "OperationNo"
DataGridView1.Rows(i).Cells("OperationNo") = OPno
i = i + 1
End With
Next
Sqlconn.Close()
Catch ex As Exception
'MessageBox.Show(ex.Message)
End Try
End Sub
This is the code to add dynamically add the data into DatagridViewComboboxColumn

how to pull the data from database to combo box

i am trying to pull the data from database to combo box , i have 2 combo box and i want to display data from different tables.
this is the code i was trying.
Try
'declare variables
Dim objDataAdapter As New SqlDataAdapter
Dim objDataAdapter1 As New SqlDataAdapter
Dim objDataSet As New DataSet()
Dim objDataSet1 As New DataSet()
'//state dataset of combo box
' Set the SelectCommand properties...
objDataAdapter.SelectCommand = New SqlCommand()
objDataAdapter.SelectCommand.Connection = sql.SqlConn
objDataAdapter.SelectCommand.CommandText = "select * from tblBrand"
objDataAdapter.SelectCommand.CommandType = CommandType.Text
'//mention the second data
objdataadapter1.SelectCommand = New SqlCommand()
objDataAdapter1.SelectCommand.Connection = sql.SqlConn
objDataAdapter1.SelectCommand.CommandText = "select * from tblModel"
objDataAdapter1.SelectCommand.CommandType = CommandType.Text
' Open the database connection...
sql.SqlConn.Open()
' Fill the DataSet object with data...
objDataAdapter.Fill(objDataSet, "tblBrand")
objDataAdapter1.Fill(objDataSet1, "tblModel")
' Close the database connection...
sql.SqlConn.Close()
With (cboxBrandName)
.DataSource = objDataSet
.ValueMember = "tblBrand.BandID"
.DisplayMember = "tblBrand.BrandName"
End With
With (cboxModel)
.DataSource = objDataSet1
.ValueMember = "tblModel.ModelID"
.DisplayMember = "tblModel.ModelName"
End With
Catch ex As Exception
End Try
End Sub
in this line not showing any error but i cannot find any result in combo box.
Here's how I do it -
Dim ds As New DataSet()
Dim conn As New SqlConnection(yourconnectionString)
Const qry As String = "SELECT * FROM tblModel"
conn.Open()
Using da As New SqlDataAdapter(qry, conn)
da.Fill(ds)
End Using
' For Combobox
With YourComboBoxName
.DisplayMember = "what you want to display to the user in combobox"
.ValueMember = "ID associated with each record"
.DataSource = ds.Tables(0)
.SelectedIndex = 0
End With
conn.Close()
Hope this helps.

Sending updates from datagridview to existing row in database

I am retrieving records from a database with the following code.
Dim SearchID As Integer = teacherID
Dim NewStudentID As Integer = studentID
Dim DisplayTable As New DataTable()
Dim da As New OleDbDataAdapter()
Dim sqlquery As String = ("select * from tblAppointments WHERE TeacherID =" & teacherID & "")
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Try
da.SelectCommand = New OleDbCommand(sqlquery, conn)
da.Fill(Finalds, "Display")
DisplayTable = Finalds.Tables("Display")
DisplayTable.Columns.Remove("Instrument")
DisplayTable.Columns.Remove("Room")
DisplayTable.Columns.Remove("TeacherID")
Registersgridview.DataSource = DisplayTable
Registersgridview.Columns(0).Visible = False
conn.Close()
Catch ex As Exception
MsgBox("There are no appointments in the database for " + Tutorcombox.Text)
End Try
It also there then added to a datagridview and certain columns are removed and some are hidden aswell.
Because its essentially a register, when the use clicks on the datagridview field that is a boolean it changes from false to true. I have been trying to send this back to the database, but have had no luck. I have tried the following :
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next
But have had no luck with doing so, as it crashes without an error.
Can anyone help?
I solved the problem myself, if any of you are having similar problems here is the solution
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
Dim appID As Integer = Registersgridview.Rows(i).Cells(0).Value
Dim present As Boolean = Registersgridview.Rows(i).Cells(4).Value
row = dt.Rows.Add
row.Item("appID") = appID
row.Item("Present") = present
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "UPDATE tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(1))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.Connection = conn
.ExecuteNonQuery()
End With
Next
conn.Close()
Registersgridview.DataSource = Nothing
dt.Clear()
try this:
Dim dt As DataTable = New DataTable("SendTable")
Dim row As DataRow
dt.Columns.Add("appID", Type.GetType("System.Int32"))
dt.Columns.Add("Present", Type.GetType("System.Boolean"))
For i = 0 To Registersgridview.Rows.Count - 1
row = dt.Rows.Add
row.Item("appID") = Registersgridview.Rows(i).Cells(0)
row.Item("Present") = Registersgridview.Rows(i).Cells(5)
Next
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
Dim sqlquery As String = "Update tblAppointments SET Present = #Present WHERE appID = #appID"
Dim sqlcommand As New OleDbCommand
For Each newrow As DataRow In dt.Rows
With sqlcommand
.CommandText = sqlquery
.Parameters.AddWithValue("#Present", newrow.Item(5))
.Parameters.AddWithValue("#appID", newrow.Item(0))
.ExecuteNonQuery()
End With
conn.Close()
Next

How to refresh datagridview without refresh button?

How can I automatically refresh and view the new current datagridview after add or delete?
what code should I put after "msgbox" to view the current data?
Private Sub add()
Dim conn As New OleDbConnection
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
Try
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "INSERT INTO course ( code, description)"
sSQL = sSQL & " VALUES (#cod, #des)"
cmd.CommandText = sSQL
cmd.Parameters.Add("#cod", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtcode.Text)) > 0, Me.txtcode.Text, DBNull.Value)
cmd.Parameters.Add("#des", OleDbType.VarChar).Value = IIf(Len(Trim(Me.txtdescription.Text)) > 0, Me.txtdescription.Text, DBNull.Value)
cmd.ExecuteNonQuery()
MsgBox("Data has been save.")
conn.Close()
Catch ex As Exception
MessageBox.Show("Already exist")
End Try
End Sub
You should bind your DataGridView to an appropriate DataSource, e.g. a DataTable.
Then, instead of inserting the data manually in the database, you could use a SqlDataAdapter and the DataTable your DataGridView is bound to.
Here's a simple example:
Dim cons = New SqlConnectionStringBuilder() With
{
.DataSource = "your_server",
.InitialCatalog = "your_db",
.UserID = "your_user",
.Password = "your_password"
}.ConnectionString
Dim con = New SqlConnection(cons)
con.Open()
' create a SqlDataAdapter and provide the SELECT command '
Dim adapter = New SqlDataAdapter()
Dim cb = New SqlCommandBuilder(adapter)
adapter.SelectCommand = New SqlCommand("SELECT code, description FROM course", con)
' the INSERT command can be generated '
adapter.InsertCommand = cb.GetInsertCommand()
' fill a new DataTable with data from database '
Dim dt = New DataTable()
adapter.Fill(dt)
' create a Form with DGV and Insert-Button '
Dim f = New Form()
Dim dgv = New DataGridView() With
{
.DataSource = dt,
.Dock = DockStyle.Fill
}
Dim addButton = New Button() With
{
.Text = "Add new",
.Dock = DockStyle.Bottom
}
Dim i = 0
AddHandler addButton.Click, Function(s, o)
' we insert the new data directly into the DataTable '
dt.Rows.Add(New Object() {"Some","Text"})
' and let the SqlDataAdapter handle the insert '
adapter.Update(dt)
End Function
f.Controls.Add(addButton)
f.Controls.Add(dgv)
f.ShowDialog()
Since the new data is written directly into the DataTable, the DataGridView is updated immediately.
Of course this is even easier when you use TableAdapters.