How can I specify which DataGridView columns are used when loading data from a DataTable? - vb.net

I have the following code to populate a DataGridView component.
It works fine, but column names are defined in the DataGridView and I got a duplicated set of columns, the ones coming from the original definition and the ones coming from the dataTable. So it seems that load is not making any effort to match names between DataGridView and DataTable (I carefully set them equal).
Private Sub PopulateTable()
Dim dataConnection As New MySqlConnection
Dim cmd As New MySqlCommand
Dim reader As MySqlDataReader
Dim dataTable As New DataTable
dataConnection.ConnectionString = "server=127.0.0.1;uid=user;pwd=password;database=test"
dataConnection.Open()
' Open connection and execute query
cmd.Connection = dataConnection
cmd.CommandText = "SELECT name, type, street1, street2 FROM customer;"
' Load DataTable through reader
reader = cmd.ExecuteReader
dataTable.Load(reader)
reader.Close()
' Assign DataTable to DataGridView
dataGridView.DataSource = dataTable
' Close DB connection
dataConnection.Close()
End Sub
Is it possible to match columns from DataTable to DataGridView?

Related

Add only new items from listbox to SQL

i have a listbox that users can add Countries Names into it anytime.
now i need to only add new data to check if the data is new then insert it to sql.
my code not work:
For Each i As String In listbox1.Items
Dim sql = "select * From Countries where CountryName=N'" & i & "'"
Dim adp As New SqlClient.SqlDataAdapter(sql, SQlconn)
Dim ds As New DataSet
adp.Fill(ds)
Dim dt = ds.Tables(0)
If dt.Rows.Count = 0 Then
Dim dr = dt.NewRow
dr!CountryName = i
dt.Rows.Add(dr)
Dim cmd As New SqlClient.SqlCommandBuilder(adp)
adp.Update(dt)
End If
Next
If you're loading the existing names from the database in the first place then there's no need for you to check anything. Simply query the database to populate a DataTable and bind that to the ListBox. When the user adds a new country, add it to the DataTable and it will automatically show up in the ListBox. When it's time to save, just use the same data adapter to save the DataTable and only the new records will be saved.

Add a new Column to a DataGridView control

I have a DataGridView with DataSource from a text file
If ouvrir.ShowDialog = DialogResult.OK Then
Dim sr As New StreamReader(ouvrir.FileName)
While Not sr.EndOfStream
datagridview1.Rows.Add(sr.ReadLine.Split(CChar(vbTab)))
End While
End If
Now I need to add another column from a database and I have a lot of problem with it.
While adding it show under the first column automatcally and what I want to add it as new column in the middle of the DataGridView.
My code its just:
Dim cmd As New SqlCommand("select numero from database", cn)
Dim da As New SqlDataAdapter(cmd)
Dim dt2 As New DataTable
da.Fill(dt2)
datagridview1.DataSource = dt2

How to fetch a particular column from Ms Access Database in Visual Basic

How do I read a particular column from database..
myConnection.Open()
Dim str As String = "SELECT fullname' FROM STUDENTS"
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
Dim dt As New DataTable
dt.Load(dr)
ListBox1.DataSource = dt
myConnection.Close()
Instead of getting the actual content of the database, what I get is System.Data.DataRowView
You need to set the DisplayMember property of the ListBox to the name of the column you want displayed. If you don't do that, you will see the result of calling ToString on each item, which is why you are seeing the name of the type of the items. Note that you should set the DisplayMember before setting the DataSource.

How to load data from an SQLite Database query into a textbox?

So I'm making a rota system for a project and I need a textbox to output the contracted hours of the employee that the user currently has selected in the combo box. The problem is, I have no idea how to go about it;
Sub GetContractedHours()
Dim sSql As String
Dim newds As New DataSet
Dim newdt As New DataTable
sSql = "SELECT emp_contractedhours FROM Employee WHERE emp_fn ='" & cboEmpName.Text & "%'"
Dim con As New SQLiteConnection(ConnectionString)
Dim cmd As New SQLiteCommand(sSql, con)
con.Open()
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "Employee")
newdt = newds.Tables(0)
txtUserAlertHours.DataSource = newdt
con.Close()
End Sub
Please help! :)
You don't need any of that code. Just get all the data in the first place and then bind your ComboBox and your TextBox, e.g.
Dim table As New DataTable
Dim conection As New SQLiteConnection(ConnectionString)
Dim adapter As New SQLiteDataAdapter("SELECT emp_fn, emp_contractedhours FROM Employee", connection)
adapter.Fill(table)
cboEmpName.DisplayMember = "emp_fn"
cboEmpName.DataSource = table
txtUserAlertHours.DataBindings.Add("Text", table, "emp_contractedhours")
The TextBox will then be automatically populated when you make a selection in the ComboBox. That's how data-binding works.
If you do want to query the database each time then you shouldn't use a data adapter at all. You're only retrieving one value and that's exactly what ExecuteScalar is for. Create a command with the appropriate SQL, call ExecuteScalar and assign the result to the Text of your TextBox.
If you really did want to use data-binding with the code you have (which would be silly) then you can bind just as I have demonstrated above. Just note that, if you're going to use a different DataTable each time, you need to remove the old binding first. You can do that most easily by calling Clear on the DataBindings collection, assuming you have not bound any other properties.

Populate column values from MS Access database into VB .Net Combo-Box dropdown values?

I am accessing data from Access MDB file using my application developed in VB .net 2010.
I want to get values from a particular table-column to be populated in a Combo Box dropdown.
I followed a similar thread # C# Adding data to combo-box from MS Access table but as the code is in C#, I was not able to successfully implement it. And reverted back to my previous code.
Because the Table will be updated by another application as well, every time I use my utility I need to get the latest data from that table. Hence I would like to have a feature that could get all available id from table.
Below is what I have been trying to do..
'below declared at class level.
' Dim cnnOLEDB As New OleDbConnection
' Dim cmdOLEDB As New OleDbCommand
cnnOLEDB.Open()
cmdOLEDB.CommandText = "select unique_id from tag_data"
cmdOLEDB.Connection = cnnOLEDB
Dim rdrOLEDB2 As OleDbDataReader = cmdOLEDB.ExecuteReader
If rdrOLEDB2.Read = True Then
TagComboBox1.DataSource = rdrOLEDB2.Item(0).ToString
TagComboBox1.ValueMember = "unique_id"
TagComboBox1.DisplayMember = "unique_id"
End If
rdrOLEDB2.Dispose()
rdrOLEDB2.Close()
cnnOLEDB.Close()
I would recommend filling a DataTable with your query. Then you can set the DataSource of the combobox, ValueMember & the DisplayMember.
Dim dt As New DataTable
Dim query As String = "select unique_id from tag_data"
Using connection As New OleDbConnection("your connection string")
Using command As New OleDbCommand(query, connection)
Using adapter As New OleDbDataAdapter(command)
connection.Open()
adapter.Fill(dt)
connection.Close()
End Using
End Using
End Using
If dt.Rows.Count > 0 Then
TagComboBox1.DataSource = dt
TagComboBox1.ValueMember = "unique_id"
TagComboBox1.DisplayMember = "unique_id"
End If