I am a newbie in using asp.net, I am getting a problem on how to refresh the GridView after the data is updated but it seems it's not working on my others pages. I have same code when I updated the supplier info and then the GridView1.Databind() is working but when I try to use this again on my other pages it doesn't work. Can you give an idea why is this happens?
Here is my code:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "UPDATE ProductTable SET ProductCode = ('" & lbl_productcode.Text & "'), ProductName = ('" & txt_prodname.Text & "'),ProductCategory =('" & lbl_category.Text & "'),Price =('" & txt_price.Text & "'), Quantity=('" & txt_qty.Text & "'), CategoryID=('" & lbl_catid.Text & "') WHERE ProductCategory = '" & TextBox1.Text & "'"
cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
MsgBox("RECORD UPDATED", MsgBoxStyle.Information)
GridView1.DataBind()
Call clear()
End Sub
I do not see anywhere in your code where you actually set the DataSource of your GridView before you DataBind() it. Check it out!
UPDATE:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "UPDATE ProductTable SET ProductCode = ('" & lbl_productcode.Text & "'), ProductName = ('" & txt_prodname.Text & "'),ProductCategory =('" & lbl_category.Text & "'),Price =('" & txt_price.Text & "'), Quantity=('" & txt_qty.Text & "'), CategoryID=('" & lbl_catid.Text & "') WHERE ProductCategory = '" & TextBox1.Text & "'"
cmd.Connection.Open()
Me.GridView1.DataSource = cmd.ExecuteReader()
GridView1.DataBind()
cmd.Connection.Close()
MsgBox("RECORD UPDATED", MsgBoxStyle.Information)
Call clear()
End Sub
Good luck!
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 was fetching data from database using DataReader object, but if condition is not getting true in the following code.
I'm trying to make student login page. And I'm posting the sample code where I'm getting the problem.
Dim cnn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim str3, str4 As String
Dim cmd As New SqlCommand
cmd.CommandText = "Select Name,password from Student"
cmd.Connection = cnn
cnn.Open()
Dim dr = cmd.ExecuteReader
While dr.Read
str3 = dr.Item(0)
str4 = dr.Item(1)
If (String.Equals(str3, TextBox1.Text) And String.Equals(str4, TextBox1.Text)) Then
Response.Write("Login")
Else
Response.Write("NotLogin")
End If
Response.Write(str3 & " " & str4 & "<br>")
Response.Write(TextBox1.Text & " " & TextBox2.Text & "<br>")
End While
End Sub
I have added Response.Write statement to check whether the values are correctly fetched from database or not. It turns out that the values were correctly fetched from database and even the value of those textboxes are equal to dr.Item(0) and dr.Item(1), but somehow the If statement is not working.
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