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
Related
I have a DropDownList iniwhich on page load it loads up all the data into it, however when the user wants to make a change to what text is displayed they just simply click on the dropdown and select the new one. My question is How do I make it so it saves the new text value that they choose? Here is what I have now:
Private Sub cboCure_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cboCure.SelectedIndexChanged
cboCure.AutoPostBack = True
Dim objXMLDoc As New System.Xml.XmlDocument
Dim objNodeList As System.Xml.XmlNodeList
Dim strXML As String = ""
Dim url As String = ""
MaterialStuff = New Message.Material
Dim code As String = cboCure.SelectedItem.Text
cboCure.Items.Clear()
If cboCure.Items.Count < 1 Then
strXML = Message.GetCureCodes
objXMLDoc.LoadXml(strXML)
objNodeList = objXMLDoc.GetElementsByTagName("Material_Cure")
cboCure.Items.Add("")
For Each childNode As System.Xml.XmlNode In objNodeList.Item(0).ChildNodes
cboCure.Items.Add(New System.Web.UI.WebControls.ListItem(childNode.SelectSingleNode("CureCodeLetter").InnerText,
childNode.SelectSingleNode("CureCode").InnerText))
Next
End If
cboCure.SelectedItem.Text = code
End Sub
I want the variable code to be the new text value that the user clicks but I can't seem to get it right, it keeps showing up as "" or the value that is originally displayed when the page loads.
EDIT:
Here is my Page_Load
If Not Page.IsPostBack Then
...code
else
cboCure_SelectedIndexChanged(sender, e )
end if
I have a page with two datagrids. One reads the value from a database and allows selection. When the user selects a grid it adds the data to the second datagrid. This is the code I am using for this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim dc1 As New DataColumn("NAME")
Dim dc2 As New DataColumn("PRICE")
dt.Columns.Add(dc1)
dt.Columns.Add(dc2)
Dim dr1 As DataRow = dt.NewRow()
GridView2.DataSource = dt
GridView2.DataBind()
End Sub
and
Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
Dim dr1 As DataRow = dt.NewRow()
dr1(0) = Name.ToString
dr1(1) = Price.ToString
dt.Rows.Add(dr1)
GridView2.DataSource = dt
GridView2.DataBind()
Now, this works perfectly.... but this obviously would work under a forms service. In a web based enviroment whenever a user selects a value in Grid 1 it resets the values in Grid 2 and I need that multiple rows are added to the 2nd Datagrid every time the user selects a value. The "data adding" is fired when the selectedindexchanged event takes place in GridView1. I think I need to save the data to a session/cookie but I have no idea how would I do this in the case of a datagrid. Like, what should I save and how I'd read it. Both Gridviews are under an Update Panel control so Postback should be instantaneous (if needed).
Sightly updated code...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
dt = DirectCast(Session("Purchase"), DataTable)
Else
Dim dc1 As New DataColumn("NAME")
Dim dc2 As New DataColumn("PRICE")
dt.Columns.Add(dc1)
dt.Columns.Add(dc2)
Dim dr1 As DataRow = dt.NewRow()
GridView2.DataSource = dt
GridView2.DataBind()
End If
End Sub
and
Dim dr1 As DataRow = dt.NewRow()
Session.Add("Purchase", dt)
dr1(0) = Name.ToString
dr1(1) = Price.ToString
dt.Rows.Add(dr1)
dt = DirectCast(Session("Purchase"), DataTable)
GridView2.DataSource = dt
GridView2.DataBind()
Try this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'This will load the DT into the session when the page initially loads and then skip it on subsequent page loads.
If Not IsPostBack Then
Dim dc1 As New DataColumn("NAME")
Dim dc2 As New DataColumn("PRICE")
dt.Columns.Add(dc1)
dt.Columns.Add(dc2)
Session.Add("Purchase", dt)
GridView2.DataSource = dt
GridView2.DataBind()
End If
End Sub
GridView1_SelectedIndexChanged:
'Clear out the old datasource.
GridView2.Datasource = Nothing
GridView2.DataBind()
'Pull the datatable from the session variable
dt = DirectCast(Session("Purchase"), DataTable)
'Create the new row and set the values
Dim dr1 As DataRow = dt.NewRow()
dr1(0) = Name.ToString
dr1(1) = Price.ToString
'Add the row to the table
dt.Rows.Add(dr1)
'If the session variable exists(which is should) then we overwrite it, if not we create it.
If Session("Purchase") Is Nothing Then Session.Add("Purchase", dt) Else Session("Purchase") = dt
'Reset the datasource of the datagrid
GridView2.DataSource = dt
GridView2.DataBind()
One thing I've run into doing this before is that in order for the datasource to actually update as expected I needed to do GridView2.Datasource = Nothing and GridView2.DataBind() as the very first thing in the event handler, I'm not sure why but it works when I do that and it doesn't when I don't so I didn't spend the time looking into it.
Seems to me like the problem is that when you select the first value, it creates a postback and that resets the other grid, you could disable EnableAutoPostback on your original element but i would like to know how are you manipulating the selected data.
I think you can easily accomplish this if instead of using 2 grids use one, add a column with a checkbox to grid named 'selected' and then save the selected row ids. Are you saving the selected rows to a database or how are you going to manipulate the selected rows? Another possibility is to use JQuery Drag and Drop (which in my opinion would be the most elegant solution but would require more time to code) with that, you can drag rows from one grid to another and then save the selected rows.
The GridView is bound to an Access Table, but I want to update the checkbox using the asp:ButtonField. The best I've been able to do is replace the checkbox with a string value. Below is the code I have now:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "check" Then
'Enable Editing on the GridView
GridView1.EditIndex = GridView1.SelectedIndex
'Assign value to the row selected
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
'Assign selected gridview row
Dim selectedRow As GridViewRow = GridView1.Rows(index)
'Assign checkbox cell as table cell
Dim selectedCell As TableCell = selectedRow.Cells(0)
'Assign a value to the checkbox, **but instead is replacing the checkbox**
selectedCell.Text = "True"
End If
End Sub
I think you need to use .FindControl().
The GridViewCell is not the same thing as a CheckBox control inside it. You code should probably look more like:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "check" Then
'Enable Editing on the GridView
GridView1.EditIndex = GridView1.SelectedIndex
'Assign value to the row selected
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
'Assign selected gridview row
Dim checkBox As CheckBox = GridView1.Rows(index).FindControl("checkBoxIdGoesHere")
checkBox.Checked = true 'or false or whatever based on your command.
End If
End Sub
I've had my own share of problems accessing controls from within GridViews. I solved something similar about a month ago. Assuming that your checkbox control is the only thing in that cell, you could try something like this:
'Assign a value to the checkbox
CType(GridView1.Rows(index).Cells(0).Controls(0), CheckBox).Checked = True
Try that and see if it works. If not, post back and we can take another look.
I have created a form to update an access DB table. My issue is that when the text in the text boxes is changed and the form is submitted, the .text values stay the same as they were when the datareader loaded them on the page load event. How can I submit the values that the user updates, not what is already there from page load.
Code:
Public Property vehicleid As Integer
Public Property connstring As String = "myconnectionstring..."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
vehicleid = Integer.Parse(Request.QueryString("vehicID"))
Dim svEnterdate, stocknum, make, model, color As String
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "select * from vehicle where vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
svEnterdate = dr("enterdate").ToString()
stocknum = dr("stock_num").ToString()
make = dr("make").ToString()
model = dr("model").ToString()
color = dr("color").ToString()
End While
conn.Close()
EnterDateTXT.Text = svEnterdate
StockNumTXT.Text = stocknum
MakeTxt.Text = make
ModelTXT.Text = model
ColorTxt.Text = color
End Sub
'inbetween these 2 events the user can manipulate all the controls .text values, yet the
' .text values of the submitted controls below are the same as the ones filled by the
'datareader
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SubmitBTN.Click
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "UPDATE Vehicle" & _
" SET stock_num=#stock, make=#make, model=#model, color=#color, enterdate=#enter " & _
"WHERE vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
cmd.Parameters.AddWithValue("#stock", StockNumTXT.Text)
cmd.Parameters.AddWithValue("#make", MakeTxt.Text)
cmd.Parameters.AddWithValue("#model", ModelTXT.Text)
cmd.Parameters.AddWithValue("#color", ColorTxt.Text)
cmd.Parameters.AddWithValue("#enter", EnterDateTXT.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
In your page load code, Check For Post back
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Write your code to read data from database here
End
End Sub
If you dont check for postback in your page load event, Everytime when you click the submit button, It is going to excute the code in your page load ( load the content again to the text box) first. So whatever you entered in the textbox will be overwritten by the content form the database and that will be saved back again to the database.
To undestand this. Put a breakpoint in your Page_load event code and another in your button click event code. Now enter some value in textbox and click the button and see whether your code block in pageload is executing or not.
Checking the Postback check in your page_load will fix the problem.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx
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.