array not holding value when updated - asp.net

i can add a value to array(0), but when i then add a value to array(1) it clears the value for array(0). I've tried every way I can think of to declare and create the array. My code looks like this:
Dim aryEstimateInfo() As String = New String(7) {}
Private Sub wzrdEstimateWizard_NextButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles wzrdEstimateWizard.NextButtonClick
Select Case wzrdEstimateWizard.ActiveStepIndex
Case 0 'first estimate wizard step
aryEstimateInfo(0) = rad_lstVehicleType.SelectedItem.ToString
Case 1 'second estimate wizard step
Dim DamageZoneSelected As Boolean = False
For Each cntrl As Control In pnlDamageZone.Controls
If TypeOf cntrl Is RadioButton Then
Dim RadButton As RadioButton = cntrl
If RadButton.Checked Then
DamageZoneSelected = True
DamageZone = RadButton.Text.ToString
Exit For
Else
DamageZoneSelected = False
End If
End If
Next
If DamageZoneSelected = True Then
lblDamageZoneError.Visible = False
aryEstimateInfo(1) = DamageZone
Else
'if no damage zone is selected a message is displayed
wzrdEstimateWizard.ActiveStepIndex = 2
wzrdEstimateWizard.ActiveStepIndex = 1
lblDamageZoneError.Visible = True
End If
Case 2 'third estimate wizard step
'assigns the number of dents to the estimate array
aryEstimateInfo(2) = ddlNumberOfDents.SelectedValue.ToString
'sets the average dent size in the estimate arrau
aryEstimateInfo(3) = ddlDentSize.SelectedValue.ToString
'sets the add-on code and number of oversized dents
If ddlOverSized.Enabled = True Then
'aryEstimateInfo.SetValue("3", 4)
aryEstimateInfo(4) = "3"
aryEstimateInfo(7) = ddlOverSized.SelectedValue.ToString
Else
End If
Case 3 'fourth estimate wizard step
Case Else
End Select
End Sub
I'm using this in an ASP.Net wizard control and in basic, visual studio 2010.

The problem is that each button click is posting back the page, which causes your aryEstimateInfo to be re-created on each postback.
In order to handle this situation elegantly, improve the maintenance of the page, and make it easier to debug this sort of situation in the future, I recommend the following changes:
1) Change the array to a class with properties:
Public Class EstimateInfo
Public VehicleType As String = ""
Public DamageZone As String = ""
Public NumberOfDents As String = ""
Public DentSize As String = ""
Public AddOnCode As String = ""
Public Oversized As String = ""
End Class
Note that all of the properties are declared as string, but the data types should probably be changed to more accurately reflect the underlying content.
This approach will help debugging because you can change the auto-implemented property to a getter/setter so that you can place a breakpoint to see where the value is getting cleared:
Private m_sVehicleType As String = ""
Public Property VehicleType As String
Get
Return m_sVehicleType
End Get
Set (Value As String
' You could set a breakpoint here to discover where the value is getting cleared.
m_sVehicleType = Value
End Set
End Property
And if you need to have the values in a string array for export to a different application or database, for example, you could add a method to the class to produce an appropriate string array.
2) Add a property to the page to store the current answer class in the page's ViewState so that you won't have to continuously re-populate the array. For example:
Private Property EstimateInfo As EstimateInfo
Get
' Add a new record to the viewstate if it doesn't already exist
If ViewState("EstimateInfo") Is Nothing Then
Me.EstimateInfo = New EstimateInfo
End If
Return ViewState("EstimateInfo")
End Get
Set (value As EstimateInfo)
ViewState("EstimateInfo") = value
End Set
End Property
Once you do this, your wizard code becomes much easier to understand and maintain:
Select Case wzrdEstimateWizard.ActiveStepIndex
Case 0 'first estimate wizard step
Me.EstimateInfo.VehicleType = rad_lstVehicleType.SelectedItem.ToString

when you declare the new array someehere in the code you cannot reuse it again after post back.
I suggest to build the array on finish wizard event
you can use the controls in whole steps where ever step you in
I guess it will be fine
otherwise you need to store the array after every update in session or view state but I don't like both
sorry I couldn't view example becoz I'm using mobile

Related

List.Add is replacing index 0 instead of adding to the next position. Why?

I'm using ASP.NET and Visual Basic to make a custom form, used for filling in information. Once I click a button, a function gets called that takes the bits information from that form, puts them into an object, and adds that object to a list. This is being used for a sort of queued entry system, so the form will be edited and submitted multiple times.
For some reason, instead of adding the new object in the next index position of the list, it instead replaces whatever was at 0. So, there is only ever one object in the list at the time.
Here's the custom form:
Here's my custom object, which is currently placed above my _Default class:
Public Class QueueItem
Public Property _TestName As String
Public Property _ValueID As String
Public Property _MathOperator As String
Public Property _ValueInput As Integer
Public Sub New()
End Sub
Public Sub New(ByVal TestName As String, ByVal ValueID As String, ByVal MathOperator As String, ByVal ValueInput As Integer)
_TestName = TestName
_ValueID = ValueID
_MathOperator = MathOperator
_ValueInput = ValueInput
End Sub
End Class
The list is declared above my Page_Load function, inside the _Default class, and is public. Here's that list definition:
Public QueueList As List(Of QueueItem) = New List(Of QueueItem)()
And, here's what gets called when that "Add To Queue" button is pressed:
Protected Sub AddToQueueButton_Click(sender As Object, e As EventArgs) Handles AddToQueueButton.Click
'Adds a new QueueItem to the QueueList
'Values pulled from the dropdown lists in the custom form
QueueList.Add(New QueueItem() With {
._TestName = TestName.SelectedValue,
._ValueID = ValueID.SelectedValue,
._MathOperator = MathOperator.SelectedValue,
._ValueInput = ValueInput.Text
})
'Below section is for testing
Dim test1 As String = QueueList(0)._TestName
Dim test2 As String = QueueList(0)._ValueID
Dim test3 As String = QueueList(0)._MathOperator
Dim test4 As String = QueueList(0)._ValueInput
Dim testmessage As String = test1 + " | " + test2 + " | " + test3 + " | " + test4
Dim count = QueueList.Count
Dim capacity = QueueList.Capacity
Response.Write("<script language='javascript'>alert('" + testmessage + "');</script>")
End Sub
So, as you can see, I have some test variables and stuff that I'm using to make sure this is working. Any time this gets called, an object gets added to the list, I look at the count and capacity for the list, and I display all the information in an alert.
This information for the alert is always reading from index 0. So, it shouldn't matter how many times I add information to the list, 0 should stay the same, and objects should be added at 1, then 2, and so on. Right?
Well, 0 changes any time I submit new information, and neither the count or capacity never increase past the first entry. They always display as if there's only one item in the list.
Here's me running the queue entry form twice, with two different numbers on the end:
First run:
Second run:
Since I'm always reading from index 0, that number at the end shouldn't change. It should be giving me the number that's associated with the object at index 0. And, the List.Add function should make the count and capacity go up. But, none of that happens. Instead, it seems to be replacing what was at 0.
If anyone has any tips on how to fix this or can clue me in on what might be going on, that would be greatly appreciated.
Every time a request is made to your page, a new instance of your class is created to handle the request. For a post-back request, some data may be loaded - for example, the values of the fields posted to the server, and anything stored in ViewState. But data stored in fields within your page will not be persisted across requests.
The code is not replacing the item at index 0; it is adding an item to an empty list.
You need to persist your list between requests somehow. You can either store it in the Session, or put it in the ViewState.

Can i use a single session variable to store all the field values

I have 9 pages with 10 fields in each page. Can i use a single session variable to store all the field(textbox,drop downlist,radiobuttons) values of 9 pages? If so could you give me small example inorder to proceed. Im kind of stuck.
Could you? Yes. Should you? Most likely not - though I can't say for sure without understanding what problem you are intending to solve.
Update with one sample solution
OK, I'm going to assume you want to store the values from the controls and not the controls themselves. If so, the easiest solution is stuff them in using some meaningful token to separate them. Like:
Session("MyControlValueList") = "name='txt1',value='hello'|name='txt2', value'world'"
To retrieve you would split them into a string array:
myArray = Session("MyControlValueList").Split("|")
And then iterate through to find the control/value you want.
So strictly speaking that's an answer. I still question whether it is the best answer for your particular scenario. Unfortunately I can't judge that until you provide more information.
Create a custom class with all the fields you want to save, then populate an instance of that and save that instance as a session variable.
I have something similar, but not identical - I'm saving various shipping address fields for an order, and I'm allowing the admins to update the order, either the shipping information or the order line items. Since that information is kept on separate tables, I store the shipping information in a session variable, and then compare it to what's on the form when they hit the "Update" button. If nothing has changed, I skip the update routine on the SQL Server database.
The easiest way for me to do this was to create a "OrderInfo" class. I saved the shipping information to this class, then saved that class to a session variable. Here's the code showing the class -
Public Class OrderInfo
Private v_shipname As String
Private v_add1 As String
Private v_add2 As String
Private v_city As String
Private v_state As String
Private v_zipcd As String
Private v_dateneeded As Date
Private v_billingmeth As Integer
Public Property ShipName() As String
Get
Return v_shipname
End Get
Set(value As String)
v_shipname = value
End Set
End Property
Public Property Add1() As String
Get
Return v_add1
End Get
Set(value As String)
v_add1 = value
End Set
End Property
Public Property Add2() As String
Get
Return v_add2
End Get
Set(value As String)
v_add2 = value
End Set
End Property
Public Property City() As String
Get
Return v_city
End Get
Set(value As String)
v_city = value
End Set
End Property
Public Property State() As String
Get
Return v_state
End Get
Set(value As String)
v_state = value
End Set
End Property
Public Property ZipCd() As String
Get
Return v_zipcd
End Get
Set(value As String)
v_zipcd = value
End Set
End Property
Public Property DateNeeded() As Date
Get
Return v_dateneeded
End Get
Set(value As Date)
v_dateneeded = value
End Set
End Property
Public Property BillingMeth() As Integer
Get
Return v_billingmeth
End Get
Set(value As Integer)
v_billingmeth = value
End Set
End Property
End Class
Here's the code for when I tested the concept to see if I could store a custom class in a session variable. This routine gets the order record, populates the fields in an instance of the custom class, and on the web form, as well. I save that instance to a session variable, then I initialize another new instance of that custom class, load the session variable to it. I then display the field values from the "retrieved" custom class, and what showed on the label matched what it should be -
Protected Sub LoadOrderInfo(ByVal ordID As Integer)
Dim connSQL As New SqlConnection
connSQL.ConnectionString = ConfigurationManager.ConnectionStrings("sqlConnectionString").ToString
Dim strProcName As String = "uspGetOrderInfoGeneral"
Dim cmd As New SqlCommand(strProcName, connSQL)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("OrderID", ordID)
If connSQL.State <> ConnectionState.Open Then
cmd.Connection.Open()
End If
Dim drOrderInfo As SqlDataReader
drOrderInfo = cmd.ExecuteReader
If drOrderInfo.Read Then
Dim orgOrder As New OrderInfo
orgOrder.ShipName = drOrderInfo("shipName")
orgOrder.Add1 = drOrderInfo("ShipAdd1")
orgOrder.Add2 = drOrderInfo("ShipAdd2")
orgOrder.City = drOrderInfo("ShipCity")
orgOrder.State = drOrderInfo("ShipState")
orgOrder.ZipCd = drOrderInfo("ShipZip")
orgOrder.DateNeeded = drOrderInfo("DateNeeded")
orgOrder.BillingMeth = drOrderInfo("BillingMethodID")
If Session.Item("orgOrder") Is Nothing Then
Session.Add("orgOrder", orgOrder)
Else
Session.Item("orgOrder") = orgOrder
End If
' I could just as easily populate the form from the class instance here
txtShipName.Text = drOrderInfo("shipName")
txtAdd1.Text = drOrderInfo("ShipAdd1")
txtAdd2.Text = drOrderInfo("ShipAdd2")
txtCity.Text = drOrderInfo("ShipCity")
txtState.Text = drOrderInfo("ShipState")
txtZipCd.Text = drOrderInfo("ShipZip")
selDate.Value = drOrderInfo("DateNeeded")
ddlBillMeth.SelectedValue = drOrderInfo("BillingMethodID")
End If
cmd.Connection.Close()
Dim retOrder As New OrderInfo
retOrder = Session.Item("orgOrder")
lblWelcomeMssg.Text = retOrder.ShipName & ", " & retOrder.Add1 & ", " & retOrder.City & ", " & retOrder.DateNeeded.ToShortDateString & ", " & retOrder.BillingMeth.ToString
End Sub
This might not be practical or desirable, given the number of fields you are trying to hold onto that way, but I'm not here to judge, so this is one possibility. I've worked with other projects where you create a table, and save that table as a session variable, so whatever structure you put into an object is retained if you save that object as a session variable.

add dataitem(from string array) to listview

To preface this, I've looked through several of the postings containing listviews and nothing really is comparing to what I'm trying to do.
I'm trying to take values determined through a loop that has several If Statements similar to what follows:
If Convert.ToInt32(GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_DAYS", DefaultValue)) > 0 Or _
Convert.ToInt32(GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_HRS", DefaultValue)) > 0 Or _
Convert.ToInt32(GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_MINS", DefaultValue)) > 0 Then
msChargeDays = GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_DAYS", DefaultValue)
msChargeHours = GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_HRS", DefaultValue)
msChargeMins = GetData(ds.Tables("HRIS").Rows(i), "ABS_CO_RULE_MINS", DefaultValue)
msHowPaid = "CR DAYS"
AbsenceLine() 'calls sub
End If
This block of code returns valid results from the dataset that it calls from. Now in the following code block, I am trying to assimilate values that are determined by the main code block which is about 40 if statements similar in structure to the block above, all contained within a For loop.
In the following code block I am trying to insert an object of ListViewItem type into the ListView. This is where I'm getting my error denoted by comment string following it. The function that fills the ListViewItem is at the bottom, all of the variables returned are all class variables and return valid values to the ListViewItem. I have double checked this via the debugger.
Private Sub AbsenceLine()
Dim sTypeReason As String
If msType = "" Then
sTypeReason = Left(msReason, 25)
Else
sTypeReason = msType & "--" & msReason
End If
Dim item As ListViewItem
item = New ListViewItem(ListViewItemType.DataItem)
item.DataItem = FillListView(sTypeReason)
absence_lv.Items.Add(item) 'this line here is what is givine me issues
End Sub
Private Function FillListView(typeReason As String) As IEnumerable(Of String)
Return {msDate, msVoid, msCont, msDays, msHours, msMinutes, typeReason, msChargeDays, msChargeHours,
msChargeMins, msHowPaid} 'all values returned are of String type
End Function
Now with the background:
Am I completely off base with what I'm trying to do?
Is there an easier way to do this with a gridview instead?
I think you're misusing the DataItem property of the ListViewItem class. That's really used to get the underlying object that the ListViewItem represents when the ListView itself is bound.
Since your FillListView function is returning an IEnumerable(Of String), you can just set the ListView's DataSource property to the function call.
absence_lv.Datasource = FillListView(sTypeReason)
absence_lv.Databind()
As you can see, there is no need to manually add each item.

Simple bind value to textbox in code behind using Telerik OpenAccess

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.
Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
----EDIT----
I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.
I get the same error, but at "Dim type = phonetype.First..."
The record is in the table, but it does not appear to be extracted with my code.
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
In general there are the following two possible reasons for getting this exception:
1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.
2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.
In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
Fixed it.
I was able to view the SQL string being generated by using this:
mytextbox.text = phonetype.tostring
I saw that the SQL contained "NULL= 'O'"
I did it like the example?!? However, when I added .ToString to the field being queried, it worked.
So the final looks like this:
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

DevExpress how to set and get tree node text and name at run time?

I am new in dev express technology. I am having a problem with devexpress XtraTreeList because i am unable to get node "NAME" and "TEXT" property.Please any one help me out through code.
One thing you need to keep in mind is that each node can be made up of multiple values. Based on the number of columns that are displayed. So, what you actually want to access is the particular column of a node in order to access or set the values for that column in the node.
For example:
TreeListColumn columnID1 = treeList1.Columns["Budget"];
// Get a cell's value in the first root node.
object cellValue1 = treeList1.Nodes[0][columnID1];
and
string columnID2 = "Budget";
// Get the display text of the focused node's cell
string cellText = treeList1.FocusedNode.GetDisplayText(columnID2);
Check out the devExpress documentation too. It's pretty helpful.
Maybe this example can help you:
Public Sub LoadTree()
TreeList1.Columns.Add().Name = "DisplayColumn"
Dim node1 = TreeList1.Nodes.Add("Father")
node1.Tag = "Father"
Dim node1_1 = TreeList1.Nodes.Add("Child Node")
node1_1.Tag = "Child Node"
Dim node1_1_1 = node1.Nodes.Add("This is a grandchild node")
node1_1_1.Tag = "Grandchild 1"
Dim node1_1_2 = node1.Nodes.Add("Another grandchild node")
node1_1_2.Tag = "Grandchild 2"
End Sub
Public Sub DisplayNodeValue(ByVal tag As String)
Dim valueToPresent = FirstTagValueInNode(TreeList1.Nodes, tag)
MsgBox(valueToPresent.ToString)
End Sub
Public Function FirstTagValueInNode(ByVal nodes As DevExpress.XtraTreeList.Nodes.TreeListNodes, ByVal tagSearch As Object)
For Each node As DevExpress.XtraTreeList.Nodes.TreeListNode In nodes
If node.Tag = tagSearch Then
Return node.GetValue(TreeList1.Columns(0))
End If
If node.Nodes.Count > 0 Then
Return FirstTagValueInNode(node.Nodes, tagSearch)
End If
Next
Return Nothing
End Function

Resources