Cannot Find Column when filtering - mysql

I am using vb.net to try and fill a combobox with values from my MySQL database which works fine by inserting the code below:
Dim strSQL As String = "SELECT distinct Department FROM users"
Dim da As New MySqlDataAdapter(strSQL, connectionString)
Dim ds As New DataSet
da.Fill(ds, "users")
With Find_Dep
.Items.Add("Select")
.DisplayMember = "Department"
.ValueMember = "Department"
.DataSource = ds.Tables("users")
.SelectedIndex = 0
End With
I have three two queries which rely on TextBoxes to search my DataGrid which also work fine. I am trying to use the current code to allow my ComboBox to grab the values from MySQL and filter them specific values from the datagrid:
Dim DV As New DataView(dbDataSet1)
DV.RowFilter = String.Format("[Department] Like '%" & Find_Dep.Text & "%'")
DataGridView1.DataSource = DV
This code above works fine if i manually add the pre-defined values into the ComboBox without populating the ComboBox from MySQL. So there is a conflict between the two and i cant figure out what it is as i am new to VB.
Retrieving error message: .Cannot Find Column[Department]' upon adding both chunks of code above. Whats the conflict?
Any help would be greatly appreciated :)

Try to fix your quotes. Opened and closed.Number of quotes must be even.

Related

why does my datagridview not show any results?

I'm new to vb.net and am trying to display results from a mysql server in my datagridview. Can anyone maybe point out whats wrong with my code? Thanks in advance.
Leaving out my connection string for safety, but it does connect. And if I put a breakpoint in the code it does fill the dataset with the correct data
Dim con As New MySqlConnection("server=;user id=;password=;database=")
con.Open()
Dim adp As New MySqlDataAdapter("Select CONCAT(FirstName,' ',Surname) as Name, LeaveDaysAvailable as 'Leave Days Available' from leave_database.Employees;", con)
Dim ds As New DataSet()
adp.Fill(ds)
dgvMain.DataSource = ds
con.Close()
This is the result. No errors....
this is the result if i run the same query in mysql workbench
A DataSet doesn't contain data directly. It has a Tables collection that contains DataTable objects and each of those contains data. If you assign a DataSet to the DataSource property of your DataGridView, you need to also set the DataMember property to tell it which DataTable to get the data from.
The problem is, you haven't named your DataTable so you have nothing to assign to the DataMember. This line:
adp.Fill(ds)
actually creates a DataTable, populates it and adds it to the Tables collection. It has no name though, so you have no name to set the DataMember to. You would need to name the DataTable first, e.g.
adp.Fill(ds, "MyDataTable")
and then you can set the DataMember:
dgvMain.DataMember = "MyDataTable"
dgvMain.DataSource = ds
The alternative is to just bind the DataTable instead of the DataSet, in which case you don't need a name:
dgvMain.DataSource = ds.Tables(0)
The thing is though, why create a DataSet in the first place if you're just going to use one DataTable? Simply create a DataTable. You can then pass that DataTable to the Fill call and assign it to the DataSource property.
dataGridView1.AutoGenerateColumns = true;
Else You have to add columns to data grid you can do it using designer file or from code like
DataGridTextColumn textColumn = new DataGridTextColumn();
dataColumn.Header = "First Name";
dataColumn.Binding = new Binding("Name");
dataGrid.Columns.Add(textColumn);
DataGridTextColumn textColumn = new DataGridTextColumn();
dataColumn.Header = "Leave day available";
dataColumn.Binding = new Binding("LeaveDaysAvailable");
dataGrid.Columns.Add(textColumn);
Using designer this will may help you https://msdn.microsoft.com/en-us/library/dyyesckz(v=vs.100).aspx

Cant get data from a specific Table in MySQL to a Vb.net Combo box

So here's my problem, I have a combo box that I want to fill with data from a table in MySql on load. I used this code for doing that:
Dim strSQL As String = "SELECT containers FROM tbl_items_containers"
Dim da As New MySqlDataAdapter(strSQL, SQLConnection)
Dim cmd As New MySqlCommand
Dim ds As New DataSet
SQLConnection.ConnectionString = ServerString
cmd.Connection = SQLConnection
da.Fill(ds, "tbl_items_containers")
With cb_container_type
.DataSource = ds.Tables("tbl_items_containers")
.DisplayMember = "containers"
.ValueMember = "containers"
.SelectedIndex = 0
End With
The error shown whenever i run it is:
An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll
Additional information: InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.
Now here's the thing, I tried getting data from another table in the same database and the code worked. My combo box was populated with data. I assumed that the problem is in the database, But I'm really lost here. I have no idea what to do. Any Ideas as to what may have cause the error? Thanks in advance.

Populating text boxes via Combobox and SQL database table

I am trying to populate a set of textboxes from a combobox on a form. The combo box is populated using a dataset when the form loads. When this is loaded it needs to show only one entry per unit number in the kitcombobox (which is a unit number for a kit with multiple pieces of equipment in it) but display the multiple pieces of equipment's information in the different text boxes when the unit number is selected via the kitcombobox. What approach should I take towards this? I'm really lost and this is all I have so far :(
Private Sub ckunit()
Dim ds As New DataSet
Dim cs As String = My.Settings.MacroQualityConnectionString
Dim kitcombobox As String = "SELECT DISTINCT Unit_Number, Status FROM Calibrated_Equipment WHERE CHARINDEX('CK', Unit_Number) > 0 AND Status='" & ckstatuscombbx.Text & "'"
Dim sqlconnect As New SqlConnection(cs)
Dim da As New SqlDataAdapter(kitcombobox, sqlconnect)
sqlconnect.Open()
da.Fill(ds, "Calibrated_Equipment")
sqlconnect.Close()
kitcombbx.DataSource = ds.Tables(0)
End Sub
Assuming you are using WinForms, I think the key will be adding an event handler for the SelectionChangedCommitted event on kitcombbx.
You can then checked the properties on the combobox to check what is selected and run another query to pull equipment information for that kit. It'd probably look something like this:
Private Sub kitcombbx_SelectionChangeCommitted(sender As Object, e As EventArgs) _
Handles kitcombbx.SelectionChangeCommitted
Dim kit = kitcombbx.SelectedItem.ToString()
Dim kitEquipment = FetchKitEquipmentInformation(kit)
PopulateEquipmentInformation(kitEquipment)
End Sub
The way you're currently constructing your query (by concatenating string parameters directly from user input) results in bad performance for most database systems, and moreover, is a huge security vulnerability. Look up SQL injection for more detail (or read these two questions).
Better DB code would probably look something like this:
Dim query = New StringBuilder()
query.AppendLine("SELECT DISTINCT Unit_Number, Status ")
query.AppendLine("FROM Calibrated_Equipment ")
query.AppendLine("WHERE CHARINDEX('CK', Unit_Number) > 0 ")
query.AppendLine(" AND Status = #STATUS ")
Dim connection As New SqlConnection(My.Settings.MacroQualityConnectionString)
Dim command As New SqlCommand(query, connection);
command.Parameters.Add("#STATUS", ckstatuscombbx.Text);
Dim da As New SqlDataAdapter(kitcombobox, sqlconnect)
'And so on...
Your question is a bit broad (and therefore, likely off-topic for StackOverflow), see How to Ask.

How To Populate A Treeview With All Columns And Values From SQL Database

Not sure if this can be done, but I am trying to generate a MySQL query that gives me each column name within a table and the values associated to those columns whilst at the same time, removing duplicate entries for the values.
In a nutshell, I am trying to populate a treeview control with the column names from a table in my database as the nodes. Under each node, I want to list all of the non duplicated and not null entries within each column as sub nodes. Basically creating a filter like control for my application.
I am trying to simulate something like the filter option in Excel where the user can tick on all of the filter options to include/exclude data.
I have tried building a query, but can only manage the column names at this stage. I have also tried building the treeview control from my dataset but can only populate the nodes, not the sub nodes.
Would appreciate any help as I am still learning SQL within VB.net
using your advice and help, I have managed to convert it to datatables and have got the desired result. Thanks for putting me on the right track.
Here's my end result. Could probably achieve the same result in a little more tidier code, but this is working for me. Thanks again.
MySQLConn.Open()
Dim ColumnQry As New MySqlCommand("SELECT * FROM Stores WHERE 1=2", MySQLConn)
ColumnQry.CommandType = CommandType.Text
Dim da1 As New MySqlDataAdapter(ColumnQry)
dasColumns.Tables.Clear()
da1.Fill(dasColumns, "Columns")
Dim dt1 As DataTable = dasColumns.Tables("Columns")
For Each f As DataColumn In dt1.Columns
trvFilter.Nodes.Add(f.ColumnName, f.ColumnName)
Dim ValuesQry As New MySqlCommand("SELECT DISTINCT " & f.ColumnName & " FROM Stores ORDER BY " & f.ColumnName, MySQLConn)
ValuesQry.CommandType = CommandType.Text
Dim da2 As New MySqlDataAdapter(ValuesQry)
dasValues.Tables.Clear()
da2.Fill(dasValues, "Values")
Dim dt2 As DataTable = dasValues.Tables("Values")
For x = 0 To (dasValues.Tables("Values").Rows.Count - 1)
trvFilter.Nodes(f.ColumnName).Nodes.Add(dt2.Rows(x)(f.ColumnName).ToString)
Next
Next
MySQLConn.Close()
I don't think you can do that with one query. Some pseudo code...
'get empty recordset, just to get all the field names
query = "SELECT * FROM mytable WHERE 1=2"
rs = conn.open(query)
'loop over the fields and add them to the treeview while storing a reference
'of the created node in variable n
foreach f in rs.fields
set n = treeview.addnode(f.name)
'for the created node get the unique values occuring in that column
query = "SELECT DISTINCT " & f.name & " FROM mytable ORDER BY " & f.name
rs2 = conn.open(query)
'loop over the found values
while not rs2.EOF
'add each value to the treeview as a child of node n
treeview.addnode(rs2.fields(f.name), n)
rs2.MoveNext
loop
next f

put the contents of the database to a combobox

I am using vb.net and mysql as the database.
I have created a field containing the abbreviations of words. My vb.net form provides a combobox which I want to connect to the field abbreviation. I want to configure the combobox so that when clicked, all the acronyms that exist in the database appear in the combobox.
Any suggestions on how I can get started?
Something like this:
Dim conn As New SqlConnection(connString)
Dim strSQL As String = "SELECT * FROM abbreviations"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "abbreviations")
With ComboBox1
.DataSource = ds.Tables("abbreviations")
.DisplayMember = "abbreviation_name"
.ValueMember = "abbreviation_id"
.SelectedIndex = 0
End With
Should give you the right idea to get started.