Copy GridView data to table in database - mysql

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.

Related

retrieve text in my mySql database and put into texbox using ODBC in vb.net

I want to retrieve a question from my db and put it into textbox for security questions but I don't know how. I am using ODBC as connection in vb.net into mysql.
Here is my code
Imports System.Data.Odbc
Public Class forgPass
Dim con As New OdbcConnection("DSN=nohdb")
Dim com As New OdbcCommand
Dim dt As DataTable
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.Open()
com = New OdbcCommand("SELECT question1 FROM sec_questions WHERE='admin'", con)
dt = New DataTable
dt.Load(com.ExecuteReader)
ques1.Text = dt.ReadXml
con.Close()
End Sub
End Class
You need to add
Imports MySql.Data.MySqlClient
I am assuming the following
You can insert the correct connection string in the con constructor. See
https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
for reference.
question1 is the name of a field in your database table.
sec_questions is the name of a table in your database.
Replace SomeFieldName with the name of field where admin is
found.
Keep your database objects local so you can control that they are closed and disposed. A single Using...End Using block handles this for you even if there is an error.
The user interface is not updated until the database objects are closed and disposed with the End Using.
To retrieve data from the DataTable you can refer to the first row in the Rows collection which is index 0. Then the column name, question1. Since the datatype is unknown until runtime we call .ToString to satisfy Option Strict.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Using con As New MySqlConnection("Your connection string"),
com As New MySqlCommand("SELECT question1 FROM sec_questions WHERE SomeFieldName ='admin';", con)
con.Open()
dt.Load(com.ExecuteReader)
End Using
ques1.Text = dt.Rows(0)("question1").ToString
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.

Add Multiple Databases in VB.NET

Is it possible to connect multiple databases to a program?
I added a database, but it was always through the "Data Source Config Wizard". My application deals with one main database, but I need to load information from other databases and add it to the main one (the user will select which database through the OpenFileDialog).
Public Class Form1
Private Sub TblTestBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TblTestBindingNavigatorSaveItem.Click
Me.Validate()
Me.TblTestBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.TestdbDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'TestdbDataSet.tblTest' table. You can move, or remove it, as needed.
Me.TblTestTableAdapter.Fill(Me.TestdbDataSet.tblTest)
End Sub
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim DBConnection As New OleDb.OleDbConnection
'''' Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ACE.OLEDB.12.0;"
'Dim dbSource As String = opnFile.ShowDialog()
opnFile.ShowDialog()
Dim ex As String = opnFile.FileName
MessageBox.Show(ex)
Dim dbSource As String = "DataSource=" & ex
MessageBox.Show(dbSource, "Data Source String", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
Dim DBDataSet As New DataSet
'''' Dim ds As New DataSet
Dim DBDataAdapter As OleDb.OleDbDataAdapter
'''' Dim da As OleDb.OleDbDataAdapter
DBConnection.ConnectionString = dbProvider & dbSource
'DBDataAdapter = (sql, DBConnection)
End Sub
End Class
Also, can someone explain to me the link in DataAdapter, DataConnection, and the DataSet? From what I see, the DataConnection is just the link that will connect the application to the database. The DataSet is your actual data from the database. So what is the DataAdapter for?
Thanks for any help!
You can add several databases using the Database wizard. You will be missing the binding navigator but you can get this easily by creating a temporary form in your project add the database to this then just copy over the binding navigator before deleting the temp form.
See this thread Display data from access using dataset The use the following.
Try something like this after you load your table into a Dataset
For Each row1 In (From dr As DataRow In yourDataSet.Tables(0).Rows Select dr Where dr("Column_Name").ToString.StartsWith(yourstring)
somestring = row1("Column_Name").ToString

Database not inserting rows through dataset and tableAdapter Vb .Net

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.

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