Updating database via Gridview manually ASP.NET (VB) - asp.net

Protected Sub GridView1_RowCommand _
(sender As Object, e As GridViewCommandEventArgs) _
Handles GridView1.RowCommand
If e.CommandName.CompareTo("command") = 0 Then
Dim itemID As Integer = Convert.ToInt32( _
GridView1.DataKeys(Convert.ToInt32(e.CommandArgument)).Value)
Dim sqlConn As New SqlConnection("connectionString")
sqlConn.Open()
Dim sqlComm As New SqlCommand("UPDATE itemTable SET property = (property + 1) WHERE id = '" + itemID + "', sqlConn")
sqlComm.ExecuteNonQuery()
sqlConn.Close()
End If
End Sub
Basically, it doesn't work and I don't get it. I've been trying to figure this out for a few days now and I can't see what I've done wrong. As you can see I'm trying to manually update a field in my database with the value of (originalvalue)+1 when the user clicks the buttonfield of the corresponding row.
I guess what I'm asking is if anyone can point out any mistakes, please do, or if there's a better way to do this (without having to go through all the DAL/BLL BS) please tell it to me.
Thank you very much!

I've solved my own problem! Look at the code:
Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
If e.CommandName = "commandname" Then
// Convert the row index stored in the CommandArgument
// property to an Integer.
Dim index = Convert.ToInt32(e.CommandArgument)
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
Dim row = GridView1.Rows(index)
// Calculate the new value.
Dim tb = CType(row.FindControl("Label1"), Label)
Dim newint As Integer = Convert.ToDouble(tb.Text) + 1
// Get the id of the idea.
Dim id As Integer = Convert.ToInt32( _
GridView1.DataKeys(index).Value)
//Manual update to the database.
Dim con As New SqlConnection("connectionstring")
Dim cmd As New SqlCommand("UPDATE ideatable SET field = " & (newint.ToString) & " WHERE id = " & (id.ToString), con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
//Refresh the page.
Page.Response.Redirect("default.aspx")
End If
End Sub
And remember to set OnRowCommand="GridView1_RowCommand" for the gridview in the aspx file code too, I forgot about that earlier! :/
I'm so happy, thanks for all the help offered! Hope this answer helps someone like me who got stuck.

I think there is problem in your sentence :- Try Below one at place of your Statement
Dim sqlComm As New SqlCommand("UPDATE itemTable SET property = (property + 1) WHERE id = " + itemID + "", sqlConn)

Watch the string you are generating and try to execute it manually and then what happens the table gets UPDATE or not.
Because I Think The "ItemId" is not there in your table.
Try to do This in SQL Server "Select * From itemTable Where id = ItemId" Because i think that the itemId is not there in your table.

Related

Deleting multiple Rows in GridView using Checkbox, Delete button outside of the Grid, without going to database

How do I delete multiple Rows in a GridView using a Checkbox, Delete button outside of the Grid, without going to database?
My purpose is to be able to delete multiple rows by SelectedCheckbox in the Gridview. After that, I use data show in gridview to make changes in database.
Dim dt As DataTable = ViewState("gridview")
Dim row As GridViewRow
For Each row In gridview.Rows
Dim SelectedRow As CheckBox = CType(row.FindControl("cbSelect"), CheckBox)
If SelectedRow.Checked Then
'gridview.rows(row.index).visible = false is not my case because those indexes are still there
End If
Next
I couldn't usegridview.rows(row.index).remove()/delete()
My 2nd option is store gridview to datatable by viewstate(). When i try to remove index in the FOR EACH loop, it showed error because after the 1st remove the datatable reindex.
Thanks for your help.
I got my 2nd option done by deleting row from bottom up.
I really appreciate If anyone could help me with my 1st option.
Dim dt As DataTable = ViewState("gridview")
For i As Integer = gridview.Rows.Count - 1 To 0 Step -1
Dim row As GridViewRow = gridview.Rows(i)
Dim SelectedRow As CheckBox = CType(row.FindControl("cbSelect"), CheckBox)
If SelectedRow.Checked Then
dt.Rows(i).Delete()
End If
Next
gridview.DataSource = dt
gridview.DataBind()
Yes, yes, delete each row from the bottom up. I believe it will be like this.
Private Sub Button_Delete_Checked_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button_Delete_Checked.Click
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("ToDelete").Value Then
MessageBox.Show(row.Cells("SomeText").Value & " will be deleted.")
End If
Next
End Sub
As for the Insert Into, this methodology should work fine.
Dim Con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Music_Sales_Database.mdb;")
Dim Com As OleDbCommand
Dim SaleCode As Integer
Dim MusicID As String
Dim SubTotalPrice As Decimal
Dim Copies1 As Integer
Dim STR1 As String
SaleCode = 1
Com = New OleDbCommand
Com.Connection = Con
Connection.open()
For x As Integer = 0 To SalesDataGridView.Rows.Count - 1
MusicID = SalesDataGridView.Rows(x).Cells(0).Value
SubTotalPrice = SalesDataGridView.Rows(x).Cells(5).Value
Copies1 = SalesDataGridView.Rows(x).Cells(3).Value
STR1 = "INSERT INTO Sales(Sales_ID, Sales_Date, Copies, Music_ID, Staff_ID, Total_Price) VALUES (#Sales_ID, #Sales_Date, #Copies, #Music_ID, #Staff_ID, #Total_Price)"
Dim Comm As New OleDbCommand(STR1, Con)
Comm.Parameters.AddWithValue("#Sales_ID", SaleCode)
Comm.Parameters.AddWithValue("#Sales_Date", txtDateAndTime)
Comm.Parameters.AddWithValue("#Copies", Copies1)
Comm.Parameters.AddWithValue("#Music_ID", MusicID)
Comm.Parameters.AddWithValue("#Staff_ID", txtStaff_ID)
Comm.Parameters.AddWithValue("#Total_Price", SubTotalPrice)
Command.ExecuteNonQuery()
Comm.Dispose()
Next
Connection.Close()
Obviously, you need to modify this to suit your specific needs.

Girdview data into parameter

I have a gridview which is going to be used to update a mysqldatabase, I only want to update 1 field,
It all works apart from getting the data from the input textbox on the gridview.
in the code below, strdocumentnumber = 77500 I want 77500 to come from the drawing No. column field of the updating row in the gridview and the value that i want to update is strAccess_Code also to come from the gridview Code column.
It all works if hard coding the values.
Private Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
'' do update..
Dim strdocumentNumber As String = 77500
Dim strAccess_Code As String = 8
dbConn = New MySqlConnection("Data Source=localhost;password=****;user id=root;database=drawlib;")
sql = "UPDATE core " & vbCrLf & _
"SET F6 ='" & strAccess_Code & "'" & vbCrLf & _
"WHERE F1 = '" & strdocumentNumber & "'"
Try
dbConn.Open()
dbcomm = New MySqlCommand(sql, dbConn)
dbread = dbcomm.ExecuteReader()
dbread.Close()
Catch myerror As MySqlException
MsgBox("Error in Saving Data: " & myerror.Message)
'dbread.Close()
Exit Sub
End Try
GridView1.EditIndex = -1
GridView1.DataSource = SqlDataSource2
GridView1.DataBind()
End Sub
thanks
I think you'll have to create a textbox in your codebehind to assign a value from your gridview textbox:
Edit
You may need to find the proper row before pulling the value from the textbox. Try this
Dim row As GridViewRow = GridView1.Rows(e.RowIndex)
If row.RowType = DataControlRowType.DataRow Then
Dim textbox As TextBox = CType(row.FindControl("nameofyourgridview textbox here"),TextBox)
strdocumentNumber = textbox.Text
End If
/Edit
In your Gridview, you'll need to change your BoundField to a TemplateField. See here for an example.
Use the designer to make the conversion (see link above) or select your column in the gridview designer and click the 'convert this column to a templatefield' button. You'll then have a textbox that you can name and grab from the code-behind.

dropdownlist is not declared. It may be inaccessible due to its protection level

As you can see from the commented out code, I'm trying to get the model dropdown be affected by + selCurrentManuf.Text.
I get this error
'selCurrentManuf' is not declared. It may be inaccessible due to its protection level.
How can this be solved?
I can access the drop down in another part of the page like this..
Dim sc1_currentmanuf As String = CType(e.Item.FindControl("selCurrentManuf"), DropDownList).Text
However in the function i am trying to use selCurrentManuf does not have access to e
Dim sc1_currentmanuf As String = CType(dlContacts.Items(0).FindControl("selCurrentManuf"), DropDownList).Text
Dim myQuery As String = "SELECT * FROM c5_model where c5_manufid = " + sc1_currentmanuf
Right click on your .aspx page, and select the command Convert To Web Application.
Then you'll be able to write:
Dim myQuery As String =
String.Format("SELECT * FROM c5_model WHERE c5_manuf = '{0}'",
selCurrentManuf.SelectedItem.Text )
I'm assuming your functions are inside a class in your App_Code or another dll and not on the code behind of the page.
If so do this instead:
I'm assuming you have something like this on your asp page code behind:
Protected Sub selCurrentManuf_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetCurrentModel(selCurrentManuf.Text)
End Sub
Change Your GetCurrentModel Code To:
Function GetCurrentModel(Byval c5_manuf as String) As DataSet
Dim mySession = System.Web.HttpContext.Current.Session
Dim myQuery As String = "SELECT * FROM c5_model " 'where c5_manuf = " + + c5_manuf
Dim myConnection As New MySqlConnection(mySession("localConn"))
myConnection.Open()
Dim myCommand As New MySqlCommand(myQuery, myConnection)
Dim myDataAdapter = New MySqlDataAdapter(myCommand)
Dim myDataset As New DataSet
myDataAdapter.Fill(myDataset, "c5_model")
Dim dr As DataRow = myDataset.Tables(0).NewRow
myDataset.Tables(0).Rows.Add(dr)
GetCurrentModel = myDataset
myConnection.Close()
End Function

How can I grab the ID of the just deleted record?

This code is intended to grab the ID of the deleted record, the user who deleted the record, and the date and time the record was deleted and insert it into a hostical table.
So far, once a record is deleted, the code grabs more than one deleted record.
Please see my code and what I am doing wrong.
Thanks alot in advance for your help.
Protected Sub GridView1_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles GridView1.RowDeleted
Dim connStr As String = ConfigurationManager.ConnectionStrings("Constr").ConnectionString
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String = ""
' Indicate whether the delete operation succeeded.
If e.Exception Is Nothing Then
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
'Who deleted a record?
sql += "Insert into Archives ([ID],[choice],[date_stamp],[approved],[chcknum],[DeletedBy],[dateDeleted]) "
sql += " SELECT [ID],[choice],[date_stamp],[approved],[chcknum],[login],getDate() from Depends "
sql += " inner join Emp on Depends.employee_id = Emp.employee_id where login ='" & Session.Item("UserName").ToString & "' and upass = '" & Session.Item("Password").ToString & "' and [ID] = '" & strID & "' "
End If
Response.Write(sql)
Response.End()
Try
cnn = New SqlConnection(connStr)
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.ExecuteNonQuery()
cmd.Dispose()
sql = ""
Catch ex As SqlException
Dim errorMsg As String = "Error in Updation"
errorMsg += ex.Message
Throw New Exception(errorMsg)
Finally
cnn.Close()
End Try
End Sub
My problem, I think, lies in this line of code:
Dim strID As String = GridView1.FindControl("ID").Cells(1).Text
I don't think it is correct.
I'm guessing you're looking for the GridView.DataKeys property. Use it to tell your GridView which column(s) in the data is should use as an unique identifer.
You probably also want to look into a few other optimzations for your code:
Use parameters in your query, don't concatenate a SQL statement like that.
Use the Using statement with your SqlConnection and SqlCommand objects for proper and easy disposal.
You're not achiving anything with the try-catch, in fact you're obscuring the exception stack.
Update:
See the GridViewDeletedEventArgs.Keys Property to get the ID of the deleted row. Is the "ID" column part of the query you're using to bind the GridView?
Here's a better (complete) example:
.aspx:
<asp:GridView ID="GridView1" DataKeyNames="ID" AutoGenerateDeleteButton="true" runat="server">
</asp:GridView>
Code-behind, with some dummy data:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim x() = {New With {.id = 1, .name = "xxx"}, New With {.id = 2, .name = "zzz"}}
GridView1.DataSource = x
GridView1.DataBind()
End If
End Sub
Private Sub GridView1_RowDeleting(sender As Object, e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
Dim id As Integer = CInt(e.Keys(0))
' Do your stuff!
' Don't forget to rebind the GridView, it will still have the deleted row in Viewstate.
End Sub
End Class
If you are running SQL Server, It might be easier to use a delete trigger on the table.
http://msdn.microsoft.com/en-us/library/aa258254%28v=SQL.80%29.aspx
...deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is attempted, and hold the old values or new values of the rows that may be changed by the user action.

whats the problem with this code?

I HAVE EDITED THIS BUT THE SAME PROBLEM :
Protected Sub SqlDataSource1_Updated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
For Each myRow As GridViewRow In GridView1.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
Dim lab4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET Travels = #travels WHERE travelid = #travelid"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#travels", lab4.Text)
cmd.Parameters.AddWithValue("#travelid", lab1.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Next
End Sub
ERROR : OBJECT REFERENCE IS NOT SET TO THE INSTANCE OF AN OBJECT
Error is in this line : Dim strSql As String = "UPDATE a1_ticket SET Travels = '" & lab4.Text & "' WHERE travelid =" & lab1.Text
travelid is Text so it should be travelid='" & lab4.Text & "'".
I strongly suspect that this is going to be the culprit:
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
Dim lab4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
FindControl returns null/Nothing if it can't find a control with that ID. My guess is that because you've got potentially multiple rows, the IDs of the controls within each row are autogenerated with extra information. I suggest you look at the HTML on the page and see what's being generated... you may want to look at finding a better way of finding an individual control within a row.
As mentioned in comments, you should then parameterize your SQL statements to avoid SQL injection attacks.

Resources