update data in vb oledb - asp.net

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

Related

The ConnectionString not initialized

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.

insert command inserts several rows in table

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 do I resolve "Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow' error?

We have a dropdownlist in gridview that gets populated from the database.
There is a also a textbox next to this dropdownlist.
If the option the user is looking for isn't in the dropdown, enter that value into the textbox and when submitted to the database, will now become in the dropdownlist.
I am running into the following error:
Unable to cast object of type 'ASP.addtoroster_aspx' to type 'System.Web.UI.WebControls.GridViewRow'.
The error is on this line:
Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
I believe this error occurs because I am using an imagebutton on the markup to submit to the database.
<asp:ImageButton ID="btnSave" runat="server" ImageUrl="images/save.png"
onmouseout="this.src='images/save.png'"
onmouseover="this.src='images/save.png'"
OnClick="btnSave_Click" alt="Save Data" />
Any idea how to resolve this?
Even though this is vb, I welcome solution in c# if available.
Thank you!
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
' Try
SetRowData()
Dim table As DataTable = TryCast(ViewState("CurrentTable"), DataTable)
If table IsNot Nothing Then
For Each row As DataRow In table.Rows
Dim txLName As String = TryCast(row.ItemArray(1), String)
Dim txName As String = TryCast(row.ItemArray(2), String)
Dim txEmail As String = TryCast(row.ItemArray(3), String)
Dim txRole As String = TryCast(row.ItemArray(4), String)
Dim txPhone As String = TryCast(row.ItemArray(5), String)
Dim drpEmpl As String = TryCast(row.ItemArray(6), String)
Dim txVIP As String = TryCast(row.ItemArray(7), String)
Dim drpLCB As String = TryCast(row.ItemArray(8), String)
'Find the button
Dim button As Button = DirectCast(sender, Button)
'Find parent row
Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
'find DropDownlist and textbox
Dim ddl As DropDownList = TryCast(parentRow.FindControl("txtLoginName"), DropDownList)
Dim txtNewUser As TextBox = TryCast(parentRow.FindControl("txtNewUser"), TextBox)
If txtNewUser IsNot Nothing AndAlso ddl IsNot Nothing Then
'add new listitem here
Dim customItem As New ListItem(txtNewUser.Text, txtNewUser.Text)
ddl.Items.Add(customItem)
End If
Dim ddlvalue As String = ""
Dim idx As Integer = grvStudentDetails.EditIndex
If drpEmpl = "Other" Then
ddlvalue = DirectCast(grvStudentDetails.FindControl("txtOther"), TextBox).Text
' Else
' ddlvalue = drpEmpl
End If
If txLName IsNot Nothing OrElse txLName IsNot Nothing OrElse txEmail IsNot Nothing OrElse txRole IsNot Nothing OrElse txPhone IsNot Nothing OrElse drpEmpl IsNot Nothing OrElse txVIP IsNot Nothing OrElse drpLCB IsNot Nothing Then
' Response.Write(String.Format("{0} {1} {2} {3} {4} {5} {6} {7} <br/>", txLName, txName, txEmail, txRole, txPhone, drpEmpl, txVIP, drpLCB))
'Try
Dim dateentered As String = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")
'Response.Write(dateentered)
'Response.End()
Dim s As String
Dim count As Integer
'If LoginName already exists, alert user
s = "SELECT Count(*) FROM Employee_Roster WHERE login_id = " & txLName
'Response.Write(s)
'Response.End()
Dim connSt As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim connc As New OleDbConnection(connSt)
Dim cmdc As New OleDbCommand(s, connc)
'cmdc.Parameters.AddWithValue("login_id", txtLoginName.SelectedValue)
connc.Open()
' cmdc.ExecuteNonQuery()
count = cmdc.ExecuteScalar()
' Now let's see if we found existing record
If count > 0 Then
'Display some feedback to the user to let them know it was processed
lblResult.ForeColor = System.Drawing.Color.Green
lblResult.Text = "User already is in the Excel Sheet!"
Else
s = "INSERT INTO Employee_Roster(login_id, FullName, Email_Address, Role_Dept,Phone,Employer,VP,entryDate,Notes) VALUES "
s += "('" & txLName & "', '" & txName & "', '" & txEmail & "', '" & txRole & "', '" & txPhone & "', '" & ddlvalue & "','" & txVIP & "','" & dateentered & "', '" & drpLCB & "')"
Response.Write(s)
Response.End()
Dim connStr As String = ConfigurationManager.ConnectionStrings("allstringconstrng").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(s, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Display some feedback to the user to let them know it was processed
lblResult.ForeColor = System.Drawing.Color.Green
lblResult.Text = "Record successfully saved!"
'Clear the form
txLName = ""
txLName = ""
txEmail = ""
txRole = ""
txPhone = ""
txVIP = ""
End If
' Catch
'If the message failed at some point, let the user know
lblResult.ForeColor = System.Drawing.Color.Red
lblResult.Text = "Your record failed to save, please try again."
' End Try
End If
Next
End If
' Catch ex As Exception
'Throw New Exception(ex.Message)
' End Try
End Sub
Its very clear that your controls are residing inside your page and casting button.NamingContainer to GridViewRow is invalid.
The solution is that you don't need to use the FindControl if your controls have this property set runat="server". Just use the ID you give to them.
One more thing to point out is you need to use parametrized queries. Your queries are prone to SQL Injection . check How do I create a parameterized SQL query? Why Should I?
Dim parentRow As GridViewRow = DirectCast(button.NamingContainer, GridViewRow)
this button is out side of Gridview and this button belongs to ASP.addtoroster_aspx
but when you say button.NamingContainer it points ASP.addtoroster_aspx as it holds that
button,so casting is failing.

Exception Error must be type IListSource, IEnumerable or IDataSource. Gridview

I get a catch exp as Exception Error in which says, data source is an invalid type, it must either be of the type IListSource, IEnumerable or IDataSource.
This error comes when I try to add a new record to a database through a gridview, so I get the data from database nicely into this gridview, therefore I do not understand that I get a catch exp as exception when the database is not unavailable.
The #thesli_number OleDbType.VarChar Value = thenumber is type of number in the db.
'Add new record to DB
Protected Sub AddNewTask(ByVal sender As Object, ByVal e As EventArgs)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("txttestcat"), TextBox).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("txttestinfo"), TextBox).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("txttestnumber"), TextBox).Text
Dim strSQL As String = ""
strSQL = "" & _
"INSERT INTO [TableTest] " & _
"([test_cat], [test_info], [test_number])" & _
"VALUES (#thesli_cat, #thesli_info, #thesli_number)"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.VarChar).Value = thenumber
GridView1.DataSource = cmd
GridView1.DataBind()
'MsgBox("Row(s) Added !! ")
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
EDIT................EDIT.................EDIT...................EDIT
Ok i can now add data to the gridview, i can delete a record and i can add a new record.
But i cant get the update event to work, can u see whats wrong in this new code !?
'Update record
Protected Sub UpdateTask(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
Dim theid = Convert.ToInt32(DirectCast(GridView1.FooterRow.FindControl("lbltestid"), Label).Text)
Dim thecat As String = DirectCast(GridView1.FooterRow.FindControl("lbltestcat"), Label).Text
Dim theinfo As String = DirectCast(GridView1.FooterRow.FindControl("lbltestinfo"), Label).Text
Dim thenumber As String = DirectCast(GridView1.FooterRow.FindControl("lbltestnumber"), Label).Text
Dim strSQL As String = ""
strSQL = "" & _
"UPDATE [TableTest] " & _
"SET [test_cat] = #thesli_cat, [test_info] = #thesli_info, [test_number] = #thesli_number " & _
"WHERE [test_id] = #thesli_id"
Using conn As New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
Try
conn.Open()
Dim cmd As New OleDbCommand(strSQL, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#thesli_id", OleDbType.Integer).Value = theid
cmd.Parameters.Add("#thesli_cat", OleDbType.VarChar).Value = thecat
cmd.Parameters.Add("#thesli_info", OleDbType.VarChar).Value = theinfo
cmd.Parameters.Add("#thesli_number", OleDbType.Integer).Value = thenumber
cmd.ExecuteNonQuery()
'MsgBox("Row(s) Updated !! ")
GridView1.EditIndex = -1
GetRecords()
Catch exp As OleDbException
If True Then
MsgBox("Error trying to add current record. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Critical)
End If
Catch exp As Exception
If True Then
MsgBox("Error the Database can be unavailable atm. " & vbCrLf & "Error: " & exp.Message & "Database Error", MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
End If
End Try
End Using
End Sub
If the answer to your original question was answered in my comment above (posted below here in quotes), then you should mark this question as answered, then post an entirely new question so you get more accurate responses. This question no longer applies to your actual problem.
My answer which, in your comment, solved your original question:
That example (referring to the link in your comment above) does not directly assign an
OleDbCommand to the DataSource, because it
can't. If you look at the example the author passes the cmd variable
to the GetData function GetData(cmd), which more than likely executes
the stored procedure and returns a DataSource supported type (e.g.
IListSource, IEnumerable or IDataSource).

How to refresh the gridview?

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!

Resources