SESSION variable isn't sending data to next page with datatable - asp.net

I am trying to send the selected record of a gridview to the next page to populate the controls using Session with datatable.
I have added breakpoints and can see the datatable is populating but it does not seem to be sending over to the next page. Please Help.
Page one VB Code
Protected Sub grdClientlist_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles grdClientlist.SelectedIndexChanged
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
dt.Columns.AddRange(New DataColumn(20) {New DataColumn("clientid"), New DataColumn("name"), New DataColumn("surname"), New DataColumn("type"), New DataColumn("status"), New DataColumn("assistant"), New DataColumn("companyname"), New DataColumn("telephoneno"), New DataColumn("mobileno"), New DataColumn("faxno"), New DataColumn("email"), New DataColumn("streetaddress"), New DataColumn("streetaddress2"), New DataColumn("streettown"), New DataColumn("streetcountry"), New DataColumn("streetpostalcode"), New DataColumn("postaladdress"), New DataColumn("postaladdress2"), New DataColumn("postaltown"), New DataColumn("postalcountry"), New DataColumn("pospostalcode")})
dt.Rows.Add(grdClientlist.SelectedRow.Cells(0).Text, grdClientlist.SelectedRow.Cells(1).Text, grdClientlist.SelectedRow.Cells(2).Text, grdClientlist.SelectedRow.Cells(3).Text, grdClientlist.SelectedRow.Cells(4).Text, grdClientlist.SelectedRow.Cells(5).Text, grdClientlist.SelectedRow.Cells(6).Text, grdClientlist.SelectedRow.Cells(7).Text, grdClientlist.SelectedRow.Cells(8).Text, grdClientlist.SelectedRow.Cells(9).Text, grdClientlist.SelectedRow.Cells(10).Text, grdClientlist.SelectedRow.Cells(11).Text, grdClientlist.SelectedRow.Cells(12).Text, grdClientlist.SelectedRow.Cells(13).Text, grdClientlist.SelectedRow.Cells(14).Text, grdClientlist.SelectedRow.Cells(15).Text, grdClientlist.SelectedRow.Cells(16).Text, grdClientlist.SelectedRow.Cells(17).Text, grdClientlist.SelectedRow.Cells(18).Text, grdClientlist.SelectedRow.Cells(19).Text, grdClientlist.SelectedRow.Cells(20).Text)
Session("client") = dt
Response.Redirect("ClientDetails.aspx")
End If
End Sub
Page 2 VB code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("dt") IsNot Nothing Then
Dim dtclient As DataTable = New DataTable()
dtclient = CType(Session("client"), DataTable)
txtClientNumber.Text = dtclient.Rows.Item("clientid").ToString
txtName.Text = dtclient.Rows.Item("name").ToString
txtSurname.Text = dtclient.Rows.Item("surname").ToString
cboClientType.Text = dtclient.Rows.Item("Type").ToString
cboClientStatus.Text = dtclient.Rows.Item("status").ToString
txtAssisstant.Text = dtclient.Rows.Item("assistant").ToString
txtCompanyName.Text = dtclient.Rows.Item("companyname").ToString
txtContactTel.Text = dtclient.Rows.Item("telephoneno").ToString
txtMobileNo.Text = dtclient.Rows.Item("mobileno").ToString
txtFaxNo.Text = dtclient.Rows.Item("faxno").ToString
txtEmailAddress.Text = dtclient.Rows.Item("email").ToString
txtStreetAddress.Text = dtclient.Rows.Item("streetaddress").ToString
txtStreetAddressL2.Text = dtclient.Rows.Item("streetaddress2").ToString
txtStreetAddressSuburb.Text = dtclient.Rows.Item("streettown").ToString
txtStreetCountry.Text = dtclient.Rows.Item("streetcountry").ToString
txtStreetPostalCode.Text = dtclient.Rows.Item("streetpostalcode").ToString
txtPostalAddress.Text = dtclient.Rows.Item("postaladdress").ToString
txtPostalAddressL2.Text = dtclient.Rows.Item("postaladdress2").ToString
txtPostalAddressSuburb.Text = dtclient.Rows.Item("postaltown").ToString
txtPostalCountry.Text = dtclient.Rows.Item("postalcountry").ToString
txtPostalPostalCode.Text = dtclient.Rows.Item("pospostalcode").ToString
End If
End Sub
I have tried indexing the row and also not indexing the row both same result.

If Session("dt") IsNot Nothing Then
Change this line to the following:
If Session("client") IsNot Nothing Then

The code for your second page is referencing the session variable by an incorrect name. In your first page you do:
Session("client") = dt
This assigns the DataTable dt to the session variable client. Top get back to this data from the second page (as has already been pointed out) you will need to reference Session("client"), which is what now holds your data. The original variable dt of type DataTable was destroyed as soon as the browser was done rendering the 1st page.

Related

declare dataview using object

I have a object in previous code and it is bind on datagrid. Now I need to add sort the column. I search the web to convert the dataTable from datasource. But I got an error'DataTable must be set prior to using DataView.'
Does anyone tell me how to do it? Thanks in advance.
there is the code to bind the datagrid:
Dim thisOrder as New co.Orders(123)
dgrdOrders.DataSource=thisOrder
dgrdOrders.DataBind()
there is my code:
Private Sub dgrdOrders_SortCommand(source As Object, e As DataGridSortCommandEventArgs) Handles dgrdOrders.SortCommand
Dim dataTable As DataTable = TryCast(dgrdOrders.DataSource, DataTable)
Dim dv As New DataView(dataTable)
dv.Sort = e.SortExpression
dgrdOrders.DataSource = dv
dgrdOrders.DataBind()
End Sub
Finally I found the way to sort it:
Private Sub dgrdOrders_SortCommand(source As Object, e As DataGridSortCommandEventArgs) Handles dgrdOrders.SortCommand
Dim lstOrders As New List(Of co.Order)
For Each objOrder As co.Order In thisOrder
lstOrders.Add(objOrder)
Next
Select Case e.SortExpression
Case "Type"
lstOrders = lstOrders.OrderBy(Function(x) x.Type).ToList
Case "Region"
lstOrders = lstOrders.OrderBy(Function(x) x.Region).ToList
End Select
dgrdOrders.DataSource = lstOrders
dgrdOrders.DataBind()
End Sub

ASP.NET with VB.NET adding rows to data table don't remain after postback

I am using ASP.NET with VB.NET and I want the user add several row to data table.
I am trying to add multi row into data table in run time by (textboxes, rad combo box and check box).
I add first row second and third row.
But when I present the data table its show only the last row I enter
so the table contain only one row.
How do I keep all row in data table not only one row? I tried everything please help.
This is my code:
Dim dcItemID = New DataColumn("ItemID", GetType(Int32))
Dim dcUnit = New DataColumn("UnitID", GetType(Int32))
Dim ItemPrice = New DataColumn("ItemPrice", GetType(Int32))
Dim sellprice = New DataColumn("SellPrice", GetType(Int32))
dt.Columns.Add(dcItemID)
dt.Columns.Add(dcUnit)
dt.Columns.Add(ItemPrice)
dt.Columns.Add(sellprice)
dt.Rows.Add(Convert.ToInt32(rcItemName.SelectedValue), Convert.ToInt32(rcUnitID.SelectedValue), tbItemPrice.Text, tbSellprice.Text)
thank u all i found the answer
if any one interested this is my solution :
Public Class WebForm1
Inherits System.Web.UI.Page
Private dt As DataTable = New DataTable()
Private dr As DataRow = Nothing
Protected Sub btnSaved_Click(sender As Object, e As EventArgs) Handles btnSaved.Click
If ViewState("table") IsNot Nothing Then
dt = CType(ViewState("table"), DataTable)
End If
dr = dt.NewRow()
dr("ItemPrice") = tbItemPrice.Text
dr("SellPrice") = tbSellprice.Text
' dr("Product_Amount") = txtAmount.Text
dt.Rows.Add(dr)
ViewState("table") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dt.Columns.Add("ItemPrice")
dt.Columns.Add("SellPrice")
End Sub
End Class

add new row in gridview

UPDATE
from this i bind gridview
Public Function uplif() As DataTable
Dim dt As New DataTable()
gridvieew1.Visible = True
Try
dt.Columns.AddRange(New DataColumn(1) {New DataColumn("ID", GetType(Integer)),
New DataColumn("Name", GetType(String))}
Dim Content As String = Request.Form(textbox1.UniqueID)
For Each row As String In Content .Split(ControlChars.Lf)
If Not String.IsNullOrEmpty(row) Then
dt.Rows.Add()
Dim i As Integer = 0
For Each cell As String In row.Split(ControlChars.Tab)
If i > 1 Then
labelmessage.Text = "More than 2 columns not Allowed !!"
textbox1.Text = ""
Else
If cell.Trim() = "" Then
cell = "0"
End If
dt.Rows(dt.Rows.Count - 1)(i) = cell
i += 1
End If
Next
End If
Next
gridvieew1.DataSource = dt
gridvieew1.DataBind()
Catch Ex As Exception
labelmessage.CssClass = "alertNo"
labelmessage.Text = Ex.Message
End Try
Return dt
End Function
Protected Sub PasteToGridView(sender As Object, e As EventArgs)
uplif()
End Sub
now when i try to add new row like this
Private Sub AddNewRowToGrid()
Dim dt As DataTable = uplif()
Dim NewRow As DataRow = dt.NewRow()
dt.Rows.Add(NewRow)
gridvieew1.DataSource = dt
gridvieew1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewRowToGrid()
End Sub
this shows same output like add new row and replace previous data which is already in gridview and also this shows an error
Object reference not set to an instance of an object.
after click on add new row
ID Name
where as i want like this
ID Name
1 abc
2 def
(here new empty row when click on button )
As was pointed out in a comment to your post, the problem is in these two lines:
Dim dt As New DataTable()
...
gridview1.DataSource = dt
That creates a brand new DataTable and binds the grid view to it. You don't copy data over, and you don't alter the existing gridview's table.
The correct fix here would be to get the DataTable from the gridview's DataSource and make any changes you need to to that. Don't create a new DataTable.
Get the already assigned DataSource and then add the Row. Do not add columns as it will be already present in your datasource
Private Sub AddNewRowToGrid()
Dim dt As gridview1.DataSource
Dim NewRow As DataRow = dt.NewRow()
dt.Rows.Add(NewRow)
gridview1.DataSource = dt
gridview1.DataBind()
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewRowToGrid()
End Sub

Calling function on dynamic page in aspx code behind

I have a function loadList() that loads a dynamic list based on our database.
In element_maint.aspx.vb:
Private Sub loadList()
'load sub-organizations
Dim lstItems As cihElementList = Nothing
Dim thr As TableHeaderRow = Nothing
Dim tr As TableRow = Nothing
Dim tc As TableCell = Nothing
Dim lnk1 As HyperLink = Nothing
Dim lnk2 As HyperLink = Nothing
Dim item As cihCategoryOrgDef = Nothing
Dim rvd As Routing.RouteValueDictionary = Nothing
Dim rvdDeactivate As Routing.RouteValueDictionary = Nothing
Dim vpd As Routing.VirtualPathData = Nothing
Dim vpdDeactivate As Routing.VirtualPathData = Nothing
Dim btnAction As cihBootstrapButtonDropdown = Nothing
'*****************************************
'Build the action drop down
'Build the action button
'*****************************************
btnAction = New cihBootstrapButtonDropdown("Action", cihBootstrapButtonDropdown.buttonTypes.link)
'Existing Items
lstItems = New cihElementList()
lstItems.loadForOrganization(orgId)
For Each ele As cihElementList.elementShort In lstItems.listOfElements
tr = New TableRow
lnk1 = New HyperLink
lnk1.Text = "Edit"
lnk2 = New HyperLink
lnk2.Text = "Deactivate"
rvd = New Routing.RouteValueDictionary(New With {.action = "edit", .elementid = ele.elementId.ToString()})
rvdDeactivate = New Routing.RouteValueDictionary(New With {.action = "deactivate", .elementid = ele.elementId.ToString()})
vpd = Routing.RouteTable.Routes.GetVirtualPath(Nothing, "element_maint", rvd)
vpdDeactivate = Routing.RouteTable.Routes.GetVirtualPath(Nothing, "element_deactivate", rvdDeactivate)
btnAction.addLink("Edit", vpd.VirtualPath, False)
If (ZenCommon.CurrentUser.secLevelId = cihCommonDef.FullSiteAdmin Or ZenCommon.CurrentUser.secLevelId = cihCommonDef.OrganizationAdmin) Then 'if SuperAdmin or Campus Admin
'Need Help here
btnAction.addLink("Deactivate", vpdDeactivate.VirtualPath, False)
End If
ZenCommon.AddCell(tr, ele.eleDescr, , , "200px")
tc = New TableCell
tc.Controls.Add(New LiteralControl(btnAction.buttonHTML))
tc.Style.Add("width", "50px")
tr.Cells.Add(tc)
Me.tblList.Rows.Add(tr)
Next
End Sub
Private Sub deactivateTag()
'Goto Database, flag 'tag' as inactive
End Sub
I want the btnAction.addLink("Deactivate") to call a function in my aspx.vb. The function will go mark the tag as inactive.
Right now the 'Edit" button (just above the 'Deactivate' button, will go to a new page to allow you to edit it. I get that. But is there a way to make it so when I click my 'Deactivate' button it will just call my deactivateTag()
In your codebehind you could change your method signature
Protected Sub deactivateTag(ByRef sender as Object, ByRef e as System.EventArgs) Handles btnDeactivate.Click
and in your markup
<asp:Button ID="btnDeactivate" onClick="deactivateTag" />
Or you can add a click event for the button and call your function from that event.
Protected Sub btnDeactivate_Click(ByRef sender as Object, ByRef e as System.EventArgs) Handles btnDeactivate.Click
deactivateTag()
End Sub
It depends on whether you'll need to call deactivateTag from other controls or not.

Dynamically adding multiple rows to a ASP Datagrid

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.

Resources