Clear Databound datagridview vb.net - mysql

I have a datagridview that gets data from the database, it's working fine but then when i close the form and open it again it wont clear the previous content. It will output the previous selection with the new selection made.
I have tried this codes:
compSpecs.modelDatagridview1.DataSource = Nothing
compSpecs.modelDatagridview1.Rows.Clear()
compSpecs.modelDatagridview1.Columns.Clear()
But it still wont clear. Maybe i'm not doing it right. Please help.
This is my code:
Private Sub load_model2()
conn = New MySqlConnection
conn.ConnectionString = "server=127.0.0.1; port=3306; username=root; password=p#ssw0rd; database= atos_db"
Dim sda As New MySqlDataAdapter
Dim bsource As New BindingSource
compSpecs.modelDatagridview2.DataSource = Nothing
compSpecs.modelDatagridview2.Rows.Clear()
compSpecs.modelDatagridview2.Columns.Clear()
Try
conn.Open()
Dim query As String
query = "select * from atos_db.itemdetails_tbl left join atos_db.brand_tbl on itemdetails_tbl.brand_id = brand_tbl.brand_id left join atos_db.item_tbl on brand_tbl.item_id=item_tbl.item_id where item='" & itemCombobox2.Text & "'"
comm = New MySqlCommand(query, conn)
sda.SelectCommand = comm
sda.Fill(dbDataset)
bsource.DataSource = dbDataset
compSpecs.modelDatagridview2.DataSource = bsource
sda.Update(dbDataset)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub

Firstly, that implies that you're using the same instance of the form each time. If you create a new instance of the form each time you want to display it then there can't be anything left over from last time.
If you don't want to do that though, there's no use unbinding the grid from the data source if you're only going to rebind it again. If the data is still in the data source then the grid will just display it again. If you want to get rid of the data then you need to clear the data source. The grid displays what's in the data source so clear the data source and the grid will be cleared too.

Related

Transfer the sum of query to label

the query is working on mysql command line but how can i put the sum to the label
Dim SDA As New MySqlDataAdapter
Dim bSource As New BindingSource
Dim dbDataSet As New DataTable
Try
MysqlConn.Open()
Dim Query As String
Query = "select sum(No_Of_Case_To_Be_Deliver) from ordered= '" & totalcase.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
SDA.Fill(dbDataSet)
bSource.DataSource = dbDataSet
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
Never concatenate strings to build an Sql statement. Use parameters. You are risking damage to your database.
A DataAdapter will open and close its connection for you as part of the .Fill method. However, if it finds the connection open it leaves it open.
Glad to see you called .Dispose on your connection but you can save yourself the trouble by using `Using...End Using blocks. This will ensure that your database objects are closed and disposed even if there is an error.
Now to the code. You are not Filling or Updating anything so you don't need a DataAdapter for this query. You are not Binding anything so no BindingSource. Bad name for DataTable (dbDataSet) because a DataSet is a different type of object. Anyone trying to maintain your code could be easily confused.
By using parameters you not only save yourself from SQL injection but greatly simplify the Sql statement. No worries about double quotes, single quotes, etc.
Since you are retrieving only a single piece of data, you can use .ExecuteScalar which returns the first column of the first row of the result set.
I separated the code into a Data Access function and User Interface part. This way you can migrate your application to a different platform, say a web app, by just picking up the function as a whole.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lblTotalCases.Text = DirectCast(GetTotalCases(CInt(totalcase.Text)), String)
End Sub
Private Function GetTotalCases(OrderID As Integer) As Integer
Dim TotalCases As Integer
'I made up a query since your query didn't make sense.
Dim Query = "select sum(No_Of_Case_To_Be_Deliver) from OrderDetails Where OrderID = #ID;"
Using MysqlConn As New MySqlConnection("Your Connection String")
Using Command As New MySqlCommand(Query, MysqlConn)
Command.Parameters.Add("#ID", MySqlDbType.Int32).Value = OrderID
MysqlConn.Open()
TotalCases = CInt(Command.ExecuteScalar)
End Using
End Using
Return TotalCases
End Function

Populate Label in VB from MySQL select query

I have found a few articles that are similar to my question, and I have tried the suggestions in those articles and none of them have worked for me. What I need seems to be fairly simple and straight forward. (I am able to complete this same action with SQL Server, just not with MySQL. This 'description' information must come a MySQL db)
I have a Listbox and as the user clicks on listbox items, I would like a 'description' label to update with a value pulled from a MySQL database.
I created a public sub in the Module, and I'm calling the sub from the Listbox1_SelectedIndexChanged event (also tried Listbox1_mouseclick event).
However, everything I have tried does not update the label. Any suggestions would be greatly appreciated.
here is the code being used to pull and attempt to populate the label:
Dim conn As New MySqlConnection(My.Resources.MySqlstr)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand("select Description from resourceaccess where tid = '" & ReportPicker.ListBox1.ValueMember & "' ", conn)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
ReportPicker.Label3.Text = reader.GetString("Description")
End While
reader.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
I don't know if something else is wrong too but this definitely is:
Dim cmd As MySqlCommand = New MySqlCommand("select Description from resourceaccess where tid = '" & ReportPicker.ListBox1.ValueMember & "' ", conn)
Apart from the fact that you should be using a parameter there, the use of ValueMember can't possibly be right. That's the name of a column, not a value from that column. You should be using SelectedValue, which is the value from that column for the item that's selected.
here is what worked:
Dim cs As String = My.Resources.MySqlstr
Dim stm As String = "select Description from resourceaccess where resource = '" & ReportPicker.ListBox1.Text & "' "
Dim conn As MySqlConnection = New MySqlConnection(cs)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(stm, conn)
ReportPicker.Label3.Text = Convert.ToString(cmd.ExecuteScalar())
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try

Displaying of pdf file on datagridview with mysql

The DataGridView won't show the PDF file from MySQL, it has red x mark on the table where the pdf. I want the file name displayed on the DataGridView. I really need help. Thanks alot. I'm using VB.Net and Workbench.
Private Sub Admin_Handouts_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
MysqlConn = New MySqlConnection
MysqlConn.ConnectionString = "server=; userid=; password=; database=cai"
MysqlConn.Open()
sql = "SELECT Code FROM cai.subjects"
command = New MySqlCommand(sql, MysqlConn)
da = New MySqlDataAdapter
dt = New DataTable
da.SelectCommand = command
da.Fill(dt)
dgvfiles.DataSource = dt
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
MysqlConn.Close()
da.Dispose()
End Try
End Sub
If you have the iTextSharp library you can read the document properties from the PDF when you load it as an object.
I don't know if the file would retain the filename property when you add it to the table, though.
https://github.com/itext/itext7-dotnet

MySqlDataAdapter SelectCommand Statement

I have the following functional code:
Call ConnSettings()
Dim objDs As New DataSet
Dim Query As String
Query = "the query"
Cmd = New MySqlCommand(Query, MysqlConn)
Dim dAdapter As New MySqlDataAdapter
dAdapter.SelectCommand = Cmd
''Dim dAdapter As New MySqlDataAdapter(Query, MysqlConn)
Try
MysqlConn.Open()
dAdapter.Fill(objDs)
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
I have noticed that the code is equally functional if I also use
Dim dAdapter As New MySqlDataAdapter(Query, MysqlConn)
instead of:
Cmd = New MySqlCommand(Query, MysqlConn)
Dim dAdapter As New MySqlDataAdapter
dAdapter.SelectCommand = Cmd
Obviously, I would like to use a single line instead of three. However, I am fairly new to VB and would like to know if there are any issues with doing that.
Let's try to improve your code....
First ConnSettings doesn't initialize a global connection variable but a local one and returns it
Public Function ConnSettings() As MySqlConnection
Dim conn As MySqlConnection
conn = new MySqlConnection(yourConnectionStringHere)
conn.Open()
return conn
End Function
Now the code that needs a MySqlConnection could call this ConnSettings and put the return value in a Using Statement
objDS = new DataSet()
Try
Using conn = ConnSettings()
Using dAdapter = New MySqlDataAdapter(theQuery, conn)
dAdapter.Fill(objDs)
End Using
End Using
Catch(ex as Exception
MessageBox.Show(ex.Message)
End Try
This code puts the connection returned in a Using Statement. When the code flows out of the Using Statement the connection is closed and disposed (same for the MySqlDataAdapter) As you can see there is no need for the Finally clause and the Try/Catch block is present just because you want to give an error message to your user (while this is a common practice there is no really sense to put your user in the unconfortable position to try to understand these technically dense messages, better use a log file and advise your user to send the log to you)
In this context also the code inside the ConnSettings is a bit useless. What you really need is just the connectionstring and you could write the creation of the MySqlConnection directly in the calling code.

How to get all names of the column in MySql database to display in comboBox

I Have a form and I like to retrieve all the columns in MySql database and display it using comboBox in vbNET.
I dont know how to query that.
Heres my sample codes:
conn = New MySqlConnection
conn.ConnectionString = "server=localhost; userid=root; password=root; database=dbase"
Dim da As New MySqlDataAdapter
Dim dt As New DataTable
Dim bs As New BindingSource
Dim ds As New DataSet
Try
ds.Clear()
conn.Open()
cmd = New MySqlCommand("[watt??]")
da = New MySqlDataAdapter(cmd)
da.SelectCommand.Connection = conn
da.Fill(ds, "gradelvl")
cbGradeLvl.Text = ds.Tables(0).Rows(0).Item(0)
Catch ex As MySqlException
MsgBox(ex.Message)
Finally
conn.Close()
End Try
I wish to reopen the question because the suggested duplicate link while correct is incomplete in reference to the VB.NET tag.
You could extract informations about your table columns also using the GetSchema method of your connection....
For example
Using cnn = new MySqlConnection(.....)
cnn.Open()
Dim dt = cnn.GetSchema("Columns", new string () {Nothing, Nothing, "gradelvl"})
for each row in dt.Rows
cbGradeLvl.Items.Add(row("COLUMN_NAME").ToString)
Next
End Using
You can get an understanding of the inner working of GetSchema looking at the MSDN docs on the SqlConnection page. I don't know if the MySql Connector supports all the options or more, but that could be a starting point for other searches