开发者

Iteratively Reference Controls by Name Pattern (VB.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 hun开发者_如何转开发dreds 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜