dtatgridview is not clearing up? - vb.net

I have searched all through the web and still cannot find the right way to clear up my datagidview for the update. It maybe because I put two datagrid view in one windows form, I don't know. Though it worked, I mean it cleared up the datasource, before I added the new datagridview.
Can anyone please help me find the solution to refresh the datagridview? I also did used the datagridview.datasource.refresh(). But it still the same?
Any Help or lead to the solution is very much appreciated, Thanks.
my code to clear the datagridview is :
least30.DataSource = Nothing
least30.CancelEdit()
least30.EndEdit()
least30.Columns.Clear()
least30.Rows.Clear()
mysqlcon.ConnectionString = "server =" + srvr + ";" + "user id =" + usrnm + ";" + "password =" + pswd + ";" + "database =" + dtb
mysqlcon.Open()
mysqlcmd.Connection = mysqlcon
mysqlcmd.CommandText = "select " & "itm" & ", sum( " & "count" & " ) from " & "dtb.tbl" & " group by " & "itm" & " order by sum( " & "count" & " ) asc limit 40"
mysqlrd = mysqlcmd.ExecuteReader
mysqldt.Load(mysqlrd)
least30.DataSource = mysqldt
mysqlrd.Close()
mysqlcon.Close()
End Sub

You should be using a data adapter. You call Fill on the data adapter to populate a DataTable and you bind that to the grid, preferably via a BindingSource. The user makes all the changes they want via the grid. You then call EndEdit on the BindingSource to ensure that any pending change is committed and then Update on the data adapter to save the changes from the DataTable back to the database. Obviously you need to populate the InsertCommand, UpdateCommand and DeleteCommand of the data adapter to save changes of those types.
Here's a quick example:
Private adapter As SqlDataAdapter
Private table As DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim builder As New SqlConnectionStringBuilder With
{
.DataSource = "MachineName\InstanceName",
.InitialCatalog = "DatabaseName",
.IntegratedSecurity = True
}
Dim connection As New SqlConnection(builder.ConnectionString)
Dim insertCommand As New SqlCommand("INSERT INTO SomeTable (SomeColumn) VALUES #SomeColumn", connection)
Dim updateCommand As New SqlCommand("UPDATE SomeTable SET SomeColumn = #SomeColumn WHERE Id = #Id", connection)
Dim deleteCommand As New SqlCommand("DELETE SomeTable WHERE Id = #Id", connection)
insertCommand.Parameters.Add("#SomeColumn", SqlDbType.VarChar, 50, "SomeColumn")
updateCommand.Parameters.Add("#SomeColumn", SqlDbType.VarChar, 50, "SomeColumn")
updateCommand.Parameters.Add("#Id", SqlDbType.Int, 0, "Id")
deleteCommand.Parameters.Add("#Id", SqlDbType.Int, 0, "Id")
adapter = New SqlDataAdapter("SELECT * FROM SomeTable", connection) With
{
.InsertCommand = insertCommand,
.UpdateCommand = updateCommand,
.DeleteCommand = deleteCommand
}
table = New DataTable
adapter.Fill(table)
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Validate()
BindingSource1.EndEdit()
adapter.Update(table)
End Sub
That code is written for SQL Server but it will be almost identical for MySQL. Just change all the System.Data.SqlClient types to the corresponding MySql.Data.MySqlClient types, e.g. SqlConnection to MySqlConnection. You would have to make some minor adjustments to the construction of the connection string and you'll need to change the SQL code and parameters to match your data but the principles all remain exactly the same.

Related

Update grid from a query

I have a Visual Basic 2010 application that uses a DataGridView to display a list of frequencies from a Microsoft Access 2010 database. The application uses the BindingNavigationPostionItem to allow navigation though the table.
The Move Next and Move Previous buttons move you up and down the list. The cool thing is, as you do this, I have code that sends the Frequency and Mode to my Yeasu radio and the radio then is set to that freq/mode.
This works great but, if I try to filter the DataGridView by the Service field, the ID field becomes blank and navigation does not work.
Here is the code that runs after you select what you want to filter by and you click the filter button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmbox1 As String
cmbox1 = ComboBox1.Text
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from HFUtil where service = '" & cmbox1 & "'", MyConn) '
da.Fill(ds, "HFUtil")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
BindingNavigator1.BindingSource = source1
DataGridView1.Refresh()
BindingNavigator1.Refresh()
'=========================================================
ListBox1.Items.Clear()
ListBox1.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ListBox1.Items.Add(sItemTemp)
Next
ComboBox2.Items.Clear()
ComboBox2.Text = ""
For Each dr As DataRow In ds.Tables(0).Rows
Dim sItemTemp As String
sItemTemp = String.Format("{0} {1} {2}", dr("freq"), dr("mode"), dr("desc"))
ComboBox2.Items.Add(sItemTemp)
Next
End Sub
The only difference between this code and the code that runs on form load is - where clause in the data adapter.
What am I doing wrong?
I don't see in your code where you apply your filter. So, lets pretend for a second that you load your whole table into DataSet. Then next thing, you either use DataSet.DefaultView or create your custom DataView and assign this to DataSource property - you did this.
Now, all you have to do is apply row filter to the data view you use
view.RowFilter = "service = '" & cmbox1 & "'"
At this point you should only see subset of records and nothing should happen to your Id field. Because your data doesn't change.
I have suspicion, you changing your view somewhere and this is why you have problems.

Adding data from Text boxes directly to database and viewing updated gridview

still very new to this and can't seem to find exactly what I'm looking for. Quick run-through on what I'm trying to accomplish. I have a datagridview (3 columns - Id, Name, Address) that is connected to a local .mdf database file, that I'm able to search through using a search textbox. My goal NOW is to submit records into the database directly using 2 text fields and the Id field to automatically increment. (Id++, txtName.Text, txtAddress.Text) and to use a send button(btnSend) to activate this event.(PLEASE KEEP IN MIND, MY GOAL IS TO HAVE EVERYONE INCLUDING THE NEW RECORD SHOW UP IN THE DATAGRIDVIEW AND FOR THE NEW ROW TO BE INSERTED DIRECTLY TO THE DATABASE AND SAVE ANY CHANGES) I've been hammering at this for a couple days now and would appreciate any help. Below is my code, but please keep in mind I'm still new and trying to figure this language out so if there's any unnecessary code, please do let me know... Also if you want to help with one additional thing, maybe some code on how to export that table to a different file from an export button. Thanks! I'm currently also getting an error saying "Cannot find table 0." when I click the btnSend button.
Public Sub btnSend_Click(ByVal sender As Object, e As EventArgs) Handles btnSend.Click
Try
Dim connectionString As String
Dim connection As SqlConnection
Dim ds As New DataSet("Table")
Dim dataset As New DataSet()
Dim sqlInsert As String
Dim sqlSelect As String
Dim Id As Integer = 5
Dim newRow As DataRow = dataset.Tables(0).NewRow()
connectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=""" & My.Application.Info.DirectoryPath & "\Database1.mdf"";Integrated Security=True;"
sqlInsert = "INSERT INTO Table (#Id, #Name, #Address) VALUES (" & Id & ", '" & txtName.Text & "','" & txtAddress.Text & "')"
sqlSelect = "SELECT * FROM Table"
connection = New SqlConnection(connectionString)
Dim da As New SqlDataAdapter()
connection.Open()
da.Fill(ds)
Using da
da.SelectCommand = New SqlCommand(sqlSelect)
da.InsertCommand = New SqlCommand(sqlInsert)
da.InsertCommand.Parameters.Add(New SqlParameter("Id", SqlDbType.Int, 4, Id))
da.InsertCommand.Parameters.Add(New SqlParameter("Name", SqlDbType.NText, 50, txtName.Text))
da.InsertCommand.Parameters.Add(New SqlParameter("Address", SqlDbType.NText, 50, txtAddress.Text))
Using dataset
da.Fill(dataset)
newRow("Id") = Id
newRow("Name") = txtName.Text
newRow("Address") = txtAddress.Text
dataset.Tables(0).Rows.Add(newRow)
da.Update(dataset)
End Using
Using newDataSet As New DataSet()
da.Fill(newDataSet)
End Using
End Using
connection.Close()
Catch ex As Exception
MsgBox(ex.Message)
Throw New Exception("Problem loading persons")
End Try
Dim updatedRowCount As String = gvDataViewer.RowCount - 1
lblRowCount.Text = "[Total Row Count: " & updatedRowCount & "]"
End Sub

Data binding to Textboxes

Dim myconn As New SqlConnection("Server=server,Trusted_Connection=True,Database=database")
'selects from mt table linking the current pc to a row
Dim sql As String = "SELECT * from idset " & vbcrlf &
"Where pcname= '" & pcname & "'"
Dim ds As New DataSet
Dim da As New SqlDataAdapter(sql, myconn)
da.Fill(ds, "Setup")
txtClientID.DataBindings.Add("text", ds.Tables("idset"), "CLID")
I don't know why its not working for some reason its not filling the data set did I declare something wrong?
The reason why it don't work is because you specify that the incoming table should be mapped to a table named Setup. Your data set doesn't contain a table named Setup, so the incoming table will be named... well, Setup.
Try this instead:
da.Fill(ds, "idset")
Also, I strongly suggest you:
Set option strict on
Always use parameterized/prepared SQL queries.
Always use the Using statement when working with disposable objects.
Seriously.
The best way to debug bindings is to use a BindingSource and handle the BindingComplete event.
Private bs As BindingSource
Private ds As DataSet
Private Sub Initialize(pcname As String)
Me.ds = New DataSet()
Using connection As New SqlConnection("Server=server,Trusted_Connection=True,Database=database")
connection.Open()
Using command As New SqlCommand()
command.Connection = connection
command.CommandText = "SELECT * from [idset] Where [pcname] = #pcname;"
command.Parameters.AddWithValue("#pcname", pcname)
Using adapter As New SqlDataAdapter(command)
adapter.Fill(Me.ds, "idset")
End Using
End Using
End Using
Me.bs = New BindingSource(Me.ds, "idset")
AddHandler bs.BindingComplete, AddressOf Me.HandleBindingCompleted
Me.txtClientID.DataBindings.Add("Text", Me.bs, "CLID")
End Sub
Private Sub HandleBindingCompleted(sender As Object, e As BindingCompleteEventArgs)
If (Not e.Exception Is Nothing) Then
Debug.WriteLine(e.ErrorText)
End If
End Sub

vb.net cannot write Query to MSAccess file

i can access to local Access Database and i can add some data using Query, but it JUST shows its data when the program is alive. when I re-execute this program, i cannot see any previously added data and so do original Database file(SourceDB.mdb).
How can I save my data? Here is my code.
Imports System.Data.OleDb
Public Class UserForm
Private myConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=.\SourceDB.mdb"
Private mDbConn As OleDbConnection
Private Sub Button_Search_Click(sender As Object, e As EventArgs) Handles Button_Search.Click
Dim myAdapter As New OleDbDataAdapter("SELECT * FROM user WHERE u_name = '" + tBoxName.Text + "'", myConn)
Dim myDataTable As New DataTable
If tBoxName.Text = "" Then
MsgBox("Input name")
Else
myAdapter.Fill(myDataTable)
If myDataTable.Rows.Count > 0 Then
tBoxPhone.Text = myDataTable.Rows(0).Item("u_phone")
tBoxAddr.Text = myDataTable.Rows(0).Item("u_addr")
tBoxBName.Text = myDataTable.Rows(0).Item("u_bname")
tBoxBAccount.Text = myDataTable.Rows(0).Item("u_baccount")
tBoxEtc.Text = myDataTable.Rows(0).Item("u_comment")
Else
MsgBox("No Name in Table")
End If
End If
End Sub
Private Sub Button_OK_Click(sender As Object, e As EventArgs) Handles Button_OK.Click
Try
If lblAOE.Text = "Add" Then
Dim myAdapter As New OleDbDataAdapter("INSERT INTO user (u_name, u_phone, u_addr, u_bname, u_baccount, u_comment) VALUES ('" + _
tBoxName.Text + "', '" + tBoxPhone.Text + "', '" + tBoxAddr.Text + "', '" + tBoxBName.Text + _
"', '" + tBoxBAccount.Text + "', '" + tBoxEtc.Text + "')", myConn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
Button_Add.Visible = True
Button_Modify.Visible = True
Button_OK.Visible = False
ClearTextBoxes()
Button_Clear.Text = "비우기"
End If Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button_Delete_Click(sender As Object, e As EventArgs) Handles Button_Delete.Click
If MessageBox.Show("Sure Wanna delete data?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Cancelled")
Exit Sub
Else
Dim myAdapter As New OleDbDataAdapter("DELETE FROM user WHERE u_name = '" + tBoxName.Text + "'", myConn)
Dim myDataTable As New DataTable
myAdapter.Fill(myDataTable)
MsgBox("DELETED")
ClearTextBoxes()
End If
End Sub
Private Sub ClientForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.UserTableAdapter.Fill(Me.SourceDBDataSet.user)
Me.Text = "User Form"
End Sub
End Class
You are using a OleDbDataAdapter trying to execute an INSERT operation (or a DELETE one), but this is not how the OleDbDataAdapter works.
An OleDbDataAdapter uses the SELECT command to retrieve the records and, if defined, its InsertCommand property to update records of a dataset through the call to the OleDbDataAdapter.Update method. You are not in this situation and you have your values directly in the textboxes. You could simply use an OleDbCommand with the appropriate sql statement (and this is the same for your DELETE method)
Try to change your code to
Dim cmdText = "INSERT INTO [user] (u_name, u_phone, u_addr, u_bname, " & _
"u_baccount, u_comment) VALUES (?, ?, ?, ?,?,?)"
Dim cmd = New OleDbCommand(cmdText, myConn)
cmd.Parameters.AddWithValue("#p1",tBoxName.Text)
cmd.Parameters.AddWithValue("#p2",tBoxPhone.Text )
cmd.Parameters.AddWithValue("#p3",tBoxAddr.Text)
cmd.Parameters.AddWithValue("#p4",tBoxBName.Text)
cmd.Parameters.AddWithValue("#p5",tBoxBAccount.Text)
cmd.Parameters.AddWithValue("#p6",tBoxEtc.Text )
cms.ExecuteNonQuery()
I have changed your string concatenation to a more correct parameterized query to avoid Sql Injection and parsing problems in case one of your textbox values contains a single quote.
you use OleDbCommand class. you make class object and use ExecuteNonQuery for insert data
like
Dim o As OleDbCommand
o.Connection = con
o.CommandType = CommandType.Text
o.CommandText = "your Query"
o.ExecuteNonQuery()
and you should use try block
try
o.ExecuteNonQuery()
catch
end try

How to Trigger Code with ComboBox Change Event

I have a created a database containing historical stock prices. On my form I have two comboboxes, ComboBox_Ticker and ComboBox_Date. When these comboboxes are filled I want to check the database and see if the respective data exists in the database. If it does I want to change the text of a label called Label_If_Present to "In Database".
My problem occurs with the change event. I want all of this to happen once I change the data in the textboxes. I have tried both the .TextChanged and .LostFocus events. The '.TextChanged' triggers the code to early and throws and error in my SQL command statement. The `.LostFocus' event doesn't do trigger my code at all.
Here is my current code:
Public databaseName As String = "G:\Programming\Nordeen Investing 3\NI3 Database.mdb"
Public con As New OleDb.OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source =" & databaseName)
Public tblName As String = "Historical_Stock_Prices"
Private Sub Change_Labels(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox_Ticker.TextChanged, ComboBox_Date.TextChanged
con.Close()
Dim dr As OleDbDataReader
con.Open()
If (File.Exists(databaseName)) Then
Dim restrictions(3) As String
restrictions(2) = tblName
Dim dbTbl As DataTable = con.GetSchema("Tables", restrictions)
If dbTbl.Rows.Count = 0 Then
Else
Dim cmd2 As New OleDb.OleDbCommand("SELECT * FROM " & tblName & " WHERE Ticker = '" & ComboBox_Ticker.Text & "' " & " AND Date1 = '" & ComboBox_Date.Text & "'", con)
dr = cmd2.ExecuteReader
If dr.Read() = 0 Then
'If record does not exist
Label_If_Present.Text = ""
Else
Label_If_Present.Text = "In Database"
End If
con.Close()
End If
Else
End If
End Sub
I have successfully implemented this concept on other forms within my project. This one is slightly different and I can't figure out why I can't get this one to work.
Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value.
Then check to see that both comboboxes have values selected. Something like this should work:
If ComboBox_Ticker.Text <> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then