Database not inserting rows through dataset and tableAdapter Vb .Net - mysql

I'm trying to insert a new row into students table but its not doing anything.
Heres my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim stAdapter As New StudentSystemDBDataSetTableAdapters.studentsTableAdapter()
Dim stDataset As New StudentSystemDBDataSet()
Dim Row As StudentSystemDBDataSet.studentsRow
Row = stDataset.students.NewstudentsRow
Row.Student_no = "34"
Row.Title = "ert"
Row.Initials = "3434"
Row.Surname = "erwer"
Row.Address = "fgsfd"
Row.Postal_Code = "rwerwe"
Row.Birthdate = "gogid"
Row.Gender = "erwrwer"
stDataset.students.Rows.Add(Row)
stAdapter.Update(stDataset.students)
End Sub

The UpdateCommand, InsertCommand and 'DeleteCommand` control how your data is updated, inserted and deleted. This is SQL that is parameterized and then used by the adapter to save your changed.
If you used the wizard to create your adapter, run it again and pay attention to the parts that make your data updatable. It will create these for you, but you have to check the box that tells it to.
If you did not use the wizard, you will need to create the commands manually as well.

Related

tableadapter not deleting programatically removed datatable rows

I have a dataset linked with a MYSQL database via tableadpators and a TableAdpaterManager (all autographed through designer view). The visual studio route was setting up a DataSource and then dragging individual tables onto the form.
Now, I can update, insert and delete records in the database if I edit the datagridviews manually. However, if I remove datarows programatically, the rows are not deleted in the database.
The removal code:
Public Shared Sub RemoveDuplicateRowsViaField(dt As DataTable, RowName As String)
Dim rowList As New List(Of String)
Dim dr As DataRow
For i = dt.Rows.Count - 1 To 0 Step -1
dr = dt(i)
If rowList.Contains(dr.Item(RowName)) Then
dt.Rows.Remove(dr)
Else
rowList.Add(dr.Item(RowName))
End If
Next
dt.DataSet.AcceptChanges()
End Sub
And the 'save' code:
Private Sub SaveOrganisationsBT_Click(sender As Object, e As EventArgs) Handles SaveOrganisationsBT.Click
Me.Validate()
Me.Gi_usersBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.dbDS)
End Sub
I've tried many things including looking into the tableAdapters in dataset design view, but am at a loss. Can anyone help?
Nevermind. Solved it. It appears to be around the use of AcceptChanges on the datasource. The code below works. I've read that datarow.remove both deletes the row and accepts changes. I'm guessing if changes are accepted then the tableadapter can't discern it needs deleting from its non 'dirty' state, given changes have been accepted, thus clearing the status of the row? Just supposition. The working code:
Public Shared Sub RemoveDuplicateRowsViaField(dt As DataTable, RowName As String)
Dim rowList As New List(Of String)
Dim dr As DataRow
For i = dt.Rows.Count - 1 To 0 Step -1
dr = dt(i)
If rowList.Contains(dr.Item(RowName)) Then
dr.Delete()
Else
rowList.Add(dr.Item(RowName))
End If
Next
End Sub

DIsplay real time SQL data on web form

I am working on a small project but currently stuck in the process and your help would be much appreciated.
I am trying to display data from one of my SQL tables onto web form (asp), which will effectively be updating as long as data is being entered into the table.
I have managed to get it to work by using the META Tag which refreshes the page every 2 seconds, but I know this is not an ideal way of doing it. It was advised to me to update the web form only from server to client when there is a new inserted value, however I do not know how to approach this.
Please see below to my current code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = "Cache Refresh:" & _
Date.Now.ToLongTimeString
SqlDependency.Start(GetConnectionSTring())
Using connection As New SqlConnection(GetConnectionSTring())
Using Command As New SqlCommand(GetSQL(), connection)
Dim Dependency As New SqlCacheDependency(Command)
Dim NumberOfMinutes As Integer = 3
Dim Expires As Date = _
DateTime.Now.AddMinutes(NumberOfMinutes)
Response.Cache.SetExpires(Expires)
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Response.AddCacheDependency(Dependency)
connection.Open()
GridView1.DataSource = Command.ExecuteReader()
GridView1.DataBind()
End Using
End Using
End Sub
Private Function GetConnectionSTring() As String
Return "Data Source=xxxxxxxxx; Initial Catalog=Test; User ID=xxx; Password= xxx;"
End Function
Private Function GetSQL() As String
Return "SELECT ProductCode, ProductName, Cost FROM dbo.OrderTempTable"
End Function
Thank you for your input.
I think you have to check the DB every certain time.
THIS is for PHP but the idea is the same.
HERE another example.

Copy GridView data to table in database

I have data in a GridView and I need to copy it to a table in a database.
Let's say my first GridView is GridView1; GridView1's database source is subjects_enrolled. After I'm done using GridView1 it's data needs to clear and in addition, clear the data in the source table.
Note: The primary purpose of GridView1 is for displaying data for printing a page, but I want to save or transfer all data in GridView1 to a database table before losing the GridView1 data.
Here is my code so far:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("mcbdatabseConnectionString").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT Subject_ID, Subject, Units FROM mcbdatabse.subject_enrolled")
Using sda As New MySqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End If
txtDate.Text = Date.Today.ToString("yyyy-MM-dd")
End Sub
When you doing some unnormal activity about databases you can be sure that you are in a bad plan. So in your case i can not understand why you want to do this.
You have better ways to do this, you can put all data in one table and add a column named 'enrolld' to filter data as you want and on user click you can delete or enrol the record.
But if you want to continue this way, you we have some events in gridview that can help:
RowDeleting, RowUpdating
If a row affected the related event fires and you can get the id of the record:
protected sub GridView1_RowDeleting(byval sender as object, byval e as GridViewDeleteEventArgs)
{
dim a as object = e.Keys["Id"]
'or
dim a as object = e.Keys[0]
}
To access the id of your record and do what you want with this.

Populate a textbox with mysql data after a combobox selection

So I have 2 mysql tables, one called "Service_Details" and one called "Payment_details"
I have a combobox in my form which displays the "service_id" field from the service table.
I'm trying to code a textbox, so when I select the service id from the combobox it writes the "service" which is another field in my service details table. The service id is linked to a service.
I am getting errors 'identifier expected' at [0] and 'Value of type 'system.data.datatablecollection' cannot be converted to 'string' at dss.tables
I can't seem to get it working after browsing the internet for an hour
Here is my code:
Private Sub cbxserviceid_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbxserviceid.SelectedIndexChanged
Dim dss As New DataSet
Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID='" + cbxserviceid.Text + "'", objconnection)
Dim cmddd = New MySqlCommandBuilder(daa)
daa.Fill(dss)
txtService1.Text = dss.Tables[0].Rows[0]["Service"].ToString();
End Sub
The indexes in VB.NET are expressed using the round braces, the square brackets are used in C#
txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
Also avoid to use string concatenation for sql command texts, use always a parameterized query
Private Sub cbxserviceid_SelectedIndexChanged(......)
Dim dss As New DataSet
if cbxserviceid.SelectedIndex <> -1 Then
Dim daa As New MySqlDataAdapter("SELECT * from service_details WHERE ServiceID=#id", _
objconnection)
daa.SelectCommand.Parameters.AddWithValue("#id", Convert.ToInt32(cbxserviceid.Text))
daa.Fill(dss)
txtService1.Text = dss.Tables(0).Rows(0)("Service").ToString()
End If
End Sub
I have also removed the creation of the MySqlCommandBuilder, being the adapter a local variable it has no sense or effect (if this is all your code in this event of course).
Looking at the comments below and the chat with the poster there is also another error to fix.
When assign a DataSource, DisplayMember and ValueMember property of a combobox it is mandatory to follow a precise order to avoid unwanted side effects
cbxserviceid.DisplayMember = "ServiceID"
cbxserviceid.ValueMember = "ServiceID"
cbxserviceid.DataSource = datatable

LINQ to SQL datagridview query returns length, not value

I've got a Windows Form with a button and a datagridview. The project includes a working database connection and LINQ to SQL class. I'm trying to bind the datagridview to the LINQ to SQL.
In a code module I've got this:
Public Function DataGridList() As BindingSource
Dim NewBindingSource As New BindingSource()
Dim db As New DataClasses1DataContext()
NewBindingSource.DataSource = _
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select Block.gr6_school Distinct
Return NewBindingSource
End Function
And this button_click code in the form:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
DataGridView1.DataSource = DataGridList()
End Sub
When I click the button I get the length of the school names in the datagridview, with a column header of "length."
If I just run this very similar code in the button_click instead, the school names appear correctly in the immediate window:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim db As New DataClasses1DataContext()
Dim TestQuery =
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select Block.gr6_school Distinct
For Each block In TestQuery
Debug.Print(block)
Next
End Sub
Give this a try:
Public Function DataGridList() As BindingSource
Dim NewBindingSource As New BindingSource()
Dim db As New DataClasses1DataContext()
NewBindingSource.DataSource = _
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select New With { Key .Value = Block.gr6_school } Distinct
Return NewBindingSource
End Function
This should give it a property that the DataGridView can pick up on. The New With... creates an anonymous object with a Property named Value. The DataGridView works on this type of object by enumerating the public properties and rendering them as columns. If you had needed more than one value, you could have added additional items inside the curly braces in the same way separated by commas. See Anonymous Types (Visual Basic) for more information.
You might try adding a .ToString to the Select:
From Block In db.BLOCK_ASSIGNMENTs
Where Block.gr912_school = "Franklin"
Select Block.gr6_school.ToString Distinct
I believe that Debug.Print does an implicit conversion to .ToString when it prints to the immediate window. However, a datagrid cell treats everything as an object and displays the default property for that object.
Turns out, of course, this has been addressed often, including on SO, and here. The route I chose was to use an intermediate DataTable:
Public Function DataGridList() As DataTable
Dim NewDataTable As New DataTable
Dim db As New DataClasses1DataContext()
Dim i As Int32
Dim qry =
From Block In db.BLOCK_ASSIGNMENTs.AsEnumerable
Where Block.gr912_school = "Franklin"
Select Block.gr6_school Distinct
NewDataTable.Columns.Add("School")
For i = 0 To qry.Count - 1
NewDataTable.Rows.Add(qry(i))
Next
Return NewDataTable
End Function
This seems pretty slow the first time it runs, so I may try something else in the future, but it allows me to feed the grid via LINQ, which is what I want to work with.
(I would like to use the qry's CopyToDataTable property, but it's only available if the query returns a DataTableRows collection, or some such, and my hacking around didn't reveal how to do that.)