Iteratively Reference Controls by Name Pattern (VB.NET) - asp.net

Is there a way to iteratively reference an ASP.NET control based on it's name pattern? Perhaps by a "pointer" or something?
What I have are a large set of comboboxes (each with an associated DropDownList and TextBox control). The DropDownList always has an item selected by default, but the use may wish to submit a NULL value. I come up with the following code to handle three cases: NULL, Existing Item, New Item.
'TextBoxControl & DropDownListControl should iteratively reference their
' respective TextBox & DropDownList controls by the actual control name
If StrComp(TextBoxControl.Text, DropDownListControl.SelectedItem.ToString) = 0 Then
'When an Existing Item is selected, Do Something
ElseIf Not TextBoxControl.Text = "" Then
'When a New Item is entered, Validate & Do Something
Else
'When NULL, Do Something
End If
The problem is, with so many comboboxes, I could easily end up with hundreds of lines of code. I wish to handle this in a more dynamic way, but I do not know if it is possible to reference controls in this way. Say I wanted to reference all the TextBox Controls and DropDownList Controls, respectively.
I can do string formatting with a given naming pattern to generate a name ID for any of the controls because they are all named with the same pattern. For example by attaching a specific suffix, say "_tb" for TextBox Controls and "_ddl" for DropDownList Controls:
Left(item.SelectedItem.ToString, item.SelectedItem.ToString.Length - 3) + "_tb"
Can this sort of thing be done in VB? Ultimately, my goal is to take the value entered/selected by the user, if any, and send it to a stored procedure on SQL Server for insertion into the database.

Yes. Write your code inside of a function having parameters for the textbox and the dropdown, and then write the function in terms of those two parameters. Then you simply call that function for every set instead of copy/pasting code everywhere.
Don't attempt choosing things by name. That's fragile and imposes machine requirements on a field that'd designed for human consumption.

I am not sure if the samething that applies VBA will apply to your situation, but I had the same issue and was able to use:
Me.MultiPage1.Pages(1).Controls("ref" & i + 1).Value
where controls encompasses all controls on the userform ("Me"). So if the controls in your program conform to a consecutive naming structure it is easy handle if the above applies vb.net

Related

ASP NET Dropdown box in a user control losing viewstate

I have a usercontrol in an ASP NET web application on which I create dropdown lists based on some loaded data (from an XML file via a component in the BIN directory)
I found that I couldn't retrieve the values across postbacks, and I've been doing a fair bit of reading to figure out why. What I would like someone to explain is why the following condition exists:
Dim dd As New DropDownList
With dd
.Items.Add(New ListItem("First Item"))
.Items.Add(New ListItem("Second Item"))
.Items.Add(sts(0))
.Items.Add(sts(1))
.Items.Add(sts(2))
.Items.Add(New ListItem("Third Item"))
End With
AddHandler dd.SelectedIndexChanged, AddressOf changed
divControls.Controls.Add(dd)
In the code above the three items 'First Item', 'Second Item' and 'Third Item' all behave correctly, as you can see they are added directly to the dropdown box in code. The items sts(0), sts(1) and sts(2) are all loaded from an XML file into either an array or list of string
Interestingly, sts(0) always posts back correctly, but any subsequent items which are added from the dynamic source don't. I've tried a bunch of ways of getting my list of strings into the dropdown so that they are still there upon postback but I'm not having much luck, would be most grateful if anyone could shed some understanding on this
I figured it out - I need to give each ListItem a value, I had lazily coded just the text portion since I wasn't using ordinals in the list, but ASP NET needed the ordinal value, or the list item value, to register the item for event validation, I expect ASP NET was only able to give subsequent items in the array or list of string the same ordinal or listitem value as all the other members of the collection, since they are from the same object. Works now!

ASP.Net - Using variable value in different button click events - VB

I have a multiview with 4 views. To switch between the views I use 4 buttons and switch the multiview's activeview index to the relevant view inside the click event of each button.
In each view there are various controls to capture data. There is then a submit button at the bottom of the final view to write all the data to a database.
What I want to achieve is to capture a time stamp of when the user clicks the button to move to each view (which will ultimately be written to the database). I can assign a timestamp to a variable by using the below code in the click event of each of the 4 buttons
Dim phase1TimeStamp as string = DateTime.Now.TimeOfDay.ToString()
The problem is, when I come to write the records to the database in the click event of the submit button, it cannot see the values assigned to these time stamp variables.
Is there a way I can pass these variable values to the submit button click event or is there a different way I can achieve this altogether? Thanks
The easiest way to do this is probably by saving the variable to session, then retrieving it. You didn't say if this was ASP .NET Web Forms or MVC, so I will give you an option for each. MVC has a few different ways you can achieve this (ViewData, ViewBag, TempData, or directly to Session). I'm not quite as familiar with Web Forms but you can at least save to Session.
Web Forms
to save to session:
HttpContext.Current.Session("phase1TimeStamp") = phase1TimeStamp.ToString()
to retrieve it (you may have to cast it, depending on the type and your VB settings):
Dim myVar as String = HttpContext.Current.Session("phase1TimeStamp")
MVC
to save to session:
Session("phase1TimeStamp") = phase1TimeStamp.ToString()
to retrieve it:
Dim myVar as String = Session("phase1TimeStamp")
A note about MVC: If you want this to work across multiple sessions (I.E., for different users or even for the same user but with multiple tabs open), you will need to append the identifier ("phase1TimeStamp") in this case with some sort of unique identifier.
You can store the values in Session cache, like this:
Session("MultiView1_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
Session("MultiView2_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
Session("MultiView3_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
Session("MultiView4_Clicked_DateTime") = DateTime.Now.TimeOfDay.ToString()
The Session value will exist in memory across page requests.
Note: You can name the Session key whatever you wish, but to get the value back out you need to match that key name exactly. Also, everything in Session is stored as an Object so you will need to cast the value to a String when you want to retrieve the value.

Is it possible to have a SQLDataSource with a parameter that is based only upon the GridView that is binding to it?

I have a scenario where I want to put four identical Gridviews on the same page. (They will be on different tabs in an Ajax TabControl.) They show the same source data, but there are four corresponding groups of source data in a common underlying table. So I want to show Group 1 on Tab 1, Group 2 on Tab 2, etc. These Gridviews contain complicated controls, so I would prefer to use the same data source for all of them to avoid unnecessary repetition. The Insert and Update commands are completely identical.
So in theory I could build the Select command in such a way that I could filter the data based on the GridView that is binding to the SQLDataSource. The problem is that if I use the same SQLDataSource for all the Gridviews, I cannot find a way to have each GridView tell the SQLDataSource which one is calling it. I am thinking maybe this is not possible, because the SQLDataSource binds first before it knows what is binding to it, but I'm not sure. Can anyone think of a way to do this?
You can change the parameter value dynamically using OnSelecting event of SQLDataSource. This can be done in server side code.
Create a property which holds your current gridview unique key, which is causing SQLDataSource to fetch data from SQL database.
Assign this property unique gridview key on DataBinding event of gridview.
Based on this property change the parameter in OnSelecting event of SQLDataSource.
Let me know if I am missing something.

What is the use of InsertVisible property of BoundField in a GridView

Can any one explain to me what the use of "InsertVisible" property of BoundField in a GridView is and at what conditions we should use it? I have seen the description on msdn.com but I am not able to understand exactly.
Thanks in advance.
The GridView control is not designed for inserting data. Thus, this explanation is more applicable to a DetailsView or a FormView.
When you put a databound control into "insert mode", it turns all of the BoundFields into user input controls (TextBoxs, CheckBoxs, etc) by default. InsertVisible allows you to change this as follows:
InsertVisible = true: A user-input control will be generated. This allows a user to enter a value for that field into your datasource.
InsertVisible = false: A user input control is not to be generated, thus the user is not given the opportunity to enter a value.
This is especially useful if you plan to programatically fill out that field (with an auto-generated ID or some calculated value).
Here is the MSDN article as a reference (I realize you mention that you read the article, this is just for the sake of completeness).

Bind a Text Box to a Field Selected by SQLDataSource (VB.NET)

I'm looking for the easiest way to bind data from a SqlDataSource to textboxes dropped in Visual Studio 2008.
For example, I have 4 textboxes currently that have Address, City, State, Zip. I also have a SqlDataSource on the page fetching the ID of the record and selecting those 4 fields based on ID.
How am I able to quickly bind each box to those particular fields selected? I would think this would be really straight forward - but seems it's not. Seems like the answer is funneled towards having to create a GridView or some type of control.
Be gentle...I'm a nub :)
In general you are correct, if you want to use databinding you'll need to use an appropriate control. For this example I'd suggest using a FormView - it is designed to display the results from a single database record and uses templates, meaning you'll have complete control over the output. This article is probably a good place to start: FormView Control: Step by Step.
To read the values bound to the FormView in the code-behind class you would need to create an event handler for the FormView's DataBound event. In that event handler you would reference the controls programmatically via FindControl, like so:
Dim myLabel As Label = CType(FormViewID.FindControl("id"), Label)
Here, id would be the ID of the Label whose value you were interested in. Once you have a reference to the Label you can get its value using myLabel.Text.

Resources