Is there a way to insert a dynamically generated datatable into mysql database in asp.net?
Sub OutputQty(ByVal dt As DataTable, ByVal AdID As Integer)
Dim sql As String = ""
Dim con As New SqlConnection(Utilities.DELcon)
Dim cmd As New SqlCommand(sql, con)
con.Open()
For Each row In dt.Rows
sql = "INSERT INTO DMQtyOutput (AdID, CompanyID, StoreNumber, DemandQty) VALUES ('" & row("AdID") & "','" & row("CompanyID") & "','" & row("StoreNumber") & "','" & row("DemandQty") & "')"
cmd.CommandText = sql
cmd.ExecuteNonQuery()
Next
con.Close()
End Sub
Related
I'm doing insert username and password into database in vb.net but it gives this error:
the error image
can someone take a look what cause it?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
pro = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Amin\source\repos\Nando's\Nando's\user.accdb"
connstring = pro
myconnection.ConnectionString = connstring
myconnection.Open()
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
Dim cmd As OleDbCommand = New OleDbCommand(command, myconnection)
cmd.ExecuteNonQuery()
cmd.Dispose()
myconnection.Close()
MsgBox("Record added", MsgBoxStyle.Information)
End Sub
I change from this:
command = "insert into user ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
to this:
command = "insert into [user] ([USERNAME],[PASSWORD]) values ('" & USERNAMETextBox.Text & "','" & PASSWORDTextBox.Text & "')"
I just put a bracket at user and it is solved.
The bad thing is I was going back and forth between tutorial for days but neither of them solve it because the error was on the table name but it is finally solved. Thank you to Hursey for mentioning reserved words.
i'm gonna straight forward. i have these lines of codes. basically it's about update data based on user input. but first, the textbox will retrieve data from database, and then the user will be free to change the value/text of the textbox and when the user click a button, the system will store the new value to database.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim check As String = Session("user_id")
Dim SqlSelect As String = "SELECT * FROM Worker Where user_id='" & check & "' "
Dim con As dbConn = New dbConn()
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Try
con.open()
reader = cmd.ExecuteReader()
reader.Read()
WorkerID_.Text = reader("WorkerID").ToString()
WorkerName.Text = reader("WorkerName").ToString()
DoB.Text = reader("DoB").ToString()
Address.Text = reader("Address").ToString()
Phone.Text = reader("Phone").ToString()
Email.Text = reader("Email").ToString()
Company.Text = reader("CompanyName").ToString()
PassNum.Text = reader("PassportNum").ToString()
PassExp.Text = reader("PassportExp").ToString()
VisaExp.Text = reader("VisaExp").ToString()
Finally
reader.Close()
con.close()
End Try
End Sub
Protected Sub Update_Click(sender As Object, e As EventArgs)
Dim con As dbConn = New dbConn()
Dim SqlUpdate As String
SqlUpdate = "UPDATE Worker SET "
SqlUpdate &= "WorkerID = '" & WorkerID_.Text & "', "
SqlUpdate &= "WorkerName = '" & WorkerName.Text & "', "
SqlUpdate &= "Address = '" & Address.Text & "', "
SqlUpdate &= "Email = '" & Email.Text & "', "
SqlUpdate &= "CompanyName = '" & Company.Text & "', "
SqlUpdate &= "PassportNum = '" & PassNum.Text & "' "
SqlUpdate &= "Where user_id ='" & Session("user_id") & "'"
Dim cmd As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim rad As OleDbDataReader
Try
con.open()
rad = cmd.ExecuteReader()
Finally
rad.Close()
con.close()
Response.Redirect("~\Worker\Profile.aspx")
End Try
End Sub
based on this code, the data can't be updated. the textbox.text in update_click will retrieve the same value of textbox in page_load (which is data from database) instead of the text input by the user.
it all worked fine if i delete the code for retrieving the data from database inside page_load. did i miss something in my code?
put
If Not Page.IsPostBack Then
//code
End If
inside page_load
Good day All
i have an issue with connection string
I'm getting this exception
The ConnectionString property has not been initialized.
on the RowDataBound of the outer gridview sub routine (VB.NET)
when trying to bind data to inner gridview
the code:
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As SqlDataSource
Dim strQRY As String = ""
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
strQRY = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
'Initialize command object
Dim cmd As New SqlCommand(strQRY, conn)
Dim dsTemp As New SqlDataSource()
dsTemp.SelectCommand = strQRY
Return dsTemp
End Using
End Function
This event occurs for each row
Protected Sub gvOdv_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Dim connString As String = ConfigurationManager.ConnectionStrings("MoyensAeriensConnectionString").ConnectionString
Dim conn As New SqlConnection(connString)
conn.Open()
Dim row As GridViewRow = e.Row
Dim strSort As String = String.Empty
' Make sure we aren't in header/footer rows
If row.DataItem Is Nothing Then
Return
End If
'Find Child GridView control
Dim gv As New GridView()
gv = DirectCast(row.FindControl("gvSorties"), GridView)
'Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
If gv.UniqueID = gvUniqueID Then
gv.PageIndex = gvNewPageIndex
gv.EditIndex = gvEditIndex
'Check if Sorting used
If gvSortExpr <> String.Empty Then
GetSortDirection()
strSort = " ORDER BY " & String.Format("{0} {1}", gvSortExpr, gvSortDir)
End If
'Expand the Child grid
ClientScript.RegisterStartupScript([GetType](), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" & DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString() & "','one');</script>")
End If
'Prepare the query for Child GridView by passing the Odv ID of the parent row
gv.DataSource = ChildDataSource(DirectCast(e.Row.DataItem, DataRowView)("OdvID").ToString(), strSort)
gv.DataBind()
'Add delete confirmation message for Customer
Dim l As LinkButton = DirectCast(e.Row.FindControl("linkDeleteCust"), LinkButton)
l.Attributes.Add("onclick", "javascript:return " & "confirm('Are you sure you want to delete this Customer " & DataBinder.Eval(e.Row.DataItem, "OdvID") & "')")
End Sub
thanks (I'v been hunting this error for last 3 hours)
It looks like both code snippets use a separate connection string. ChildDataSource uses "SiteConnectionString" and gvOdv_RowDataBound uses "MoyensAeriensConnectionString", hopefully I'm not pointing out the obvious here, but if so, are both of those present in your config file?
When you have created the SqlDataSource dynamically in your first code snippet, You haven't set its ConnectionString property, that's why this error is coming up.
Note that you also haven't assigned any ID to your SqlDataSource. Its better to do this too.
You also need to set the ConnectionString property of SqlDataSource.
Dim dsTemp As New SqlDataSource()
dsTemp.ID = "mySqlSourceControl"
dsTemp.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionStr").ConnectionString
dsTemp.SelectCommand = strQRY
...
Rest of things should also be fine like: web.config has a connection string for the key mentioned [ e.g. ConnectionStr here]
Instead of returning a SQLDataSource as the gridview's datasource, perhaps return a dataset.
Private Function ChildDataSource(ByVal strCustometId As String, ByVal strSort As String) As DataSet
Dim strQRY As String = "SELECT [Sortie].[OdvID],[Sortie].[SortieID]," & "[Sortie].[Fuel],[Sortie].[Captain],[Sortie].[Crew] FROM [Sortie]" & " WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "UNION ALL " & "SELECT '" & strCustometId & "','','','','' FROM [Sortie] WHERE [Sortie].[OdvID] = '" & strCustometId & "'" & "HAVING COUNT(*)=0 " & strSort
Dim connString As String = ConfigurationManager.ConnectionStrings("SiteConnectionString").ConnectionString
Using conn As New SqlConnection(connString)
conn.Open()
Using da As New SqlDataAdapter(strQRY, conn)
Using ds As New DataSet
If da.Fill(ds) > 0 Then
Return ds
Else
Return New DataSet
End If
End Using
End Using
End Using
End Function
The method to set the datasource of the child gridview remains the same.
I'm using this code to insert in database , but every time it inserts more than one row ,what is the problem ?
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
Dim com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
con.Open()
com.ExecuteNonQuery()
con.Close()
End Using
End Sub
Have you checked to see if your block of code is being called more than once? One quick way is to put a alert box inside so you can count the times it runs.
Well... there are lots of problems. The first of which is the potential for SQL Injection, you should be using named parameters. Another is that the line about Dim com As New... should also be in a Using clause.
However, nothing in that bit of code suggests that it is inserting more than 1 record. I suggest you put a break point on the ExecuteNonQuery line and see what's going on.
I have checked and hole the button click was executed twice , I have changed the code to this one and it has been solved , but I dont know why the click event is executed twice :
Dim i As Boolean = True
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim dob As DateTime = DateTime.Parse(Request.Form(TextBox6.UniqueID))
Dim conString As String = ConfigurationManager.ConnectionStrings("sqlexpress").ConnectionString
Using con As New System.Data.SqlClient.SqlConnection(conString)
con.Open()
Using com As New SqlCommand("INSERT INTO main (GroupID, Name, Description, ModeUD, StartNum, StartDate, Rate) VALUES (" & TextBox1.Text & ",'" & TextBox2.Text & "','" & TextBox3.Text & "'," & Me.DropDownList1.SelectedItem.Value & "," & TextBox4.Text & ",'" & dob & "'," & TextBox5.Text & ")", con)
If i = True Then
com.ExecuteScalar()
i = False
End If
End Using
con.Close()
End Using
End Sub
How to apply databind, so that the recent updated value will be displyed instantly, as i press update button ?
Dim cmd As New Data.SqlClient.SqlCommand
Dim con As New Data.SqlClient.SqlConnection(constr)
Try
Dim strSql As String = "UPDATE a1_admins SET ImageURL = '" _
& "~/admin/Image/" & FileName & "' WHERE EmployeeId =" _
& Label1.Text
'------------"
con.Open()
cmd.Connection = con
cmd.CommandText = strSql
cmd.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
cmd.Dispose()
con.Dispose()
End Try
Just re-databind your control. If you post your databinding code I can provide a better answer.