Gridview - Cannot get updated cell value for RowUpdating - asp.net

I am using ItemTemplate & EditTemplate for editing the gridview. (ASP.net + VB).
I click EDIT button then I can check/uncheck those checkbox and amend the textbox value.
When click UPDATE button, it will fire the RowUpdating Event, But I found that when I get the value for update statement, it still get the value before editing, not updated value.
How can I get the latest & updated value ? Thanks.
Joe
The following is the VB code:
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Update the values.
Dim row = Gridview1.Rows(e.RowIndex)
Dim Col1_SL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_SL"), CheckBox)
Dim Col1_VL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_VL"), CheckBox)
Dim Col1_ML = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_ML"), CheckBox)
Dim Col1_PH = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_PH"), CheckBox)
Dim Col1_APH = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_APH"), CheckBox)
Dim Col1_TOIL = CType(Gridview1.Rows(e.RowIndex).FindControl("cb1_TOIL"), CheckBox)
Dim Col1_Others = CType(Gridview1.Rows(e.RowIndex).FindControl("tb1_Others"), TextBox)
Dim Col1_RosterKey = CType(Gridview1.Rows(e.RowIndex).FindControl("lb1_rosterkey"), Label)
Using conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("hris_shiftdutyConnectionString").ConnectionString)
conn.Open()
cmd.Connection = conn
sql = "SET DATEFORMAT dmy;UPDATE troster SET SL='" & Convert.ToInt32(Col1_SL.Checked) & "' where roster_key='" & Col1_RosterKey.Text & "';"
cmd.CommandText = Sql
reader = cmd.ExecuteReader()
conn.Close()
reader.Close()
End Using
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub

The most likely reason will be this.
You are calling BindData() on Page_Load without using !IsPostBack
Protected Sub Page_Load Handles Me.Load
If Not IsPostBack
' Bind Grid only at the first load
' Do not load Grid again at Postbacks
BindData()
End If
End Sub

You have 2 options:
There is a separate RowUpdated method that is fired after updates have been performed by the data source that is bound to the grid view. This method will contain the new values for edits and inserts.
The RowUpdating method should have a parameter of type GridViewEventArgs. This will have a property called NewValues that contains the new values. In your example this was the variable e.

Related

After every postback dropdownlist items repeats

I have bind my dropdownlist with database. But on each PostBack the items in dropdownlist gets repeat again.
e.g.
OnPage Load I have this items in dropdownlist 1,2,3,4.. etc Now suppose page gets postBack then it looks like 1,2,3,4,1,2,3,4
Vb code
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateAreas()
End Sub
Private Sub PopulateAreas()
If IsPostBack Then
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity Like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
UPDATE
I have master page which has dropdownlist of cities. I am using masterpage control to mycontent page like below.
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Now in my PopulateArea() class there is query in which WHERE clause have cityselector. So according to city my area gets fetched.
Call your function inside not postback event so that the dropdown is not called on postback events(which fills it everything).
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
if ispostback = false then
Me.PopulateAreas()
end if
End Sub
its pretty simple.. the page load event is triggered every time anything is post back.
use this
Private Sub hospitals_Load(sender As Object, e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
//do stuff when post back occurs
Else
Me.PopulateAreas() //put this function here so that it executes only once
End If
End Sub
If your dropdown values have to change on the postback. Say initially the values where 1,2,3,4 and on postback if the values has to be 2,3,4,5 based on some of the values you change on the form controls you will have to clear the dropdown values first and then add new values to it.
areasList.Items.Clear()
Also see that AppendDataBoundItems is not true: in your .aspx page
Change your code to,
Private Sub PopulateAreas()
If IsPostBack Then
areasList.Items.clear()
Dim citySelector As DropDownList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity Like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End If
End Sub

Visual Basic ASP.NET Not Reading Unchecked Checkbox Properly

I have a web application that reads from a SQL database to create a gridview. From this gridview I want to select some data and transfer it back to another page via session variable. I have tried to create continuity by checking the boxes previously selected, but if I uncheck them and send the information back, the unchecked box remains in the session variable data.
This is the code that checks the session variable and checks boxes accordingly.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim String1 As String = ""
Dim String2 As String = ""
Dim boolcheck As Boolean = False
For Each row As DataRow In employeelist.Rows
String1 = row.Item(0)
For Each row2 As GridViewRow In EmployeeListGridView.Rows
String2 = row2.Cells(1).Text
If String1 = String2 Then
Dim checkRow As CheckBox = TryCast(row2.Cells(0).FindControl("checkRow"), CheckBox)
checkRow.Checked = True
End If
Next
Next
End Sub
This is the code that stores a datatable to the session variable
Protected Sub SelectButton_Click(sender As Object, e As EventArgs) Handles SelectButton.Click
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn() {New DataColumn("ZID"), New DataColumn("Last Name")})
For Each row As GridViewRow In EmployeeListGridView.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim checkRow As CheckBox = TryCast(row.Cells(0).FindControl("checkRow"), CheckBox)
If checkRow.Checked Then
Dim zid As String = row.Cells(1).Text
Dim lastname As String = row.Cells(3).Text
dt.Rows.Add(zid, lastname)
End If
End If
Next
Session("employeedt") = dt
Response.Redirect("ManagerTraining.aspx")
End Sub
If a box is checked on page load from the first bit of code, unchecked by the user, the second piece of code will step into the "If checkRow.checked" statement even though the user has unchecked that box. The checkboxes are contained in a gridview. I am using ASP.NET and VB. I feel like the changes aren't being committed if the user unchecks.
Please read about the ASP.NET lifecycle.
Page.Load always executes before the event handlers on postback. You should wrap the code setting the checkbox values in
If not isPostback Then
Dim checkRow As CheckBox = TryCast(row2.Cells(0).FindControl("checkRow"), CheckBox)
checkRow.Checked = True
End If

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.

Gridview RowUpdating Error - Index was out of range

When I click the "Update" button in the gridview, it fire the RowUpdating event, but it returns a error "Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index"
The following is the vb code:
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
If e.RowIndex >= 0 Then
Dim row As GridViewRow = DirectCast(Gridview1.Rows(e.RowIndex), GridViewRow)
Dim Col1_SL As CheckBox = DirectCast(row.FindControl("cb1_SL"), CheckBox)
.................
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim sql As String
Dim reader As System.Data.SqlClient.SqlDataReader
Using conn As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("hris_shiftdutyConnectionString").ConnectionString)
conn.Open()
cmd.Connection = conn
sql = "SET DATEFORMAT dmy;UPDATE troster SET SL='" & Convert.ToInt32(Col1_SL.Checked) & "' where roster_key='" & Col1_RosterKey.Text & "';"
cmd.CommandText = sql
reader = cmd.ExecuteReader()
conn.Close()
reader.Close()
End Using
'Reset the edit index.
Gridview1.EditIndex = -1
'Bind data to the GridView control.
BindData()
End If
End Sub
Please help. Thanks
Joe
Since the ViewState is disabled and you are only databinding when the page is not being posted back, this line is always going to fail:
Dim row As GridViewRow = DirectCast(Gridview1.Rows(e.RowIndex), GridViewRow)
as the count on Gridview1.Rows is going to be 0.
When the page is posted back to the server, ASP.NET needs the ViewState to be enabled for the control so it can recreate the controls and properly determine which events to raise, which control values have changed, etc. You should enable the ViewState, and you'll have to figure out what is causing the control tree error. There must be some other modification that is taking place in the code.
Keep in mind that only databinding the GridView in Page_Load when the page is not posted back is correct, but you won't be able to properly handle events unless you enable ViewState on the control.

use gridview row control in sqldatasource insert command

I am trying to use a label from another row in the gridview and insert it in a table when the user clicks the button which is in its own column.
my problem is that i cant get bookno which finds the label set to the #bookno in my sqldatasource
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim selectedRow As Button = DirectCast(sender, Button)
Dim bookno As Label = CType(selectedRow.FindControl("label1"), Label)
Dim why As TextBox = CType(selectedRow.FindControl("textbox2"), TextBox)
Dim yesint As Integer = 1
Dim sql As SqlDataSource = CType(selectedRow.FindControl("sqldatasource4"), SqlDataSource)
sql.InsertParameters.Add(bookno.Text, 0)
sql.Insert()
End Sub
Try
Dim bookno As Label = CType(selectedRow.Parent.FindControl("label1"), Label)
and see if you get a valid control for bookno. If it works, do the same for other FindControl() calls.

Resources