Reference a Textbox using a String

R

Randy

My situation is that I have a form on which a number of textboxes and
comboboxes are added dynamically based on interaction with the user.
As these controls are added, they are given names based on how many
times the user has added the control. For example, the first textbox
is on the form at design time; its name is tbItem1. If the user adds
another textbox for items, its name is tbItem2, and so on. This all
works easily.

Where I have a problem is later on when I am trying to transfer the
text that the user places in these controls into the database. I am
using sql commands to do this. Here is my code (excerpted):

strSQL = "INSERT INTO Items (Item) VALUES @Item"
Dim cmdInsert As New SqlCommand(strSQL, cn)

for x = 1 to intItemCount
cmdInsert.Parameters.AddWithValue("@UOM", "tbItem" &
intItemCount & ".text")
cmdInsert.ExecuteNonQuery()
next

Unfortunately, this doesn't work. What winds up in the datatable is
the string value "tbItem1.text" (for the first iteration), not the
actual text in the textbox. I can easily see why this is happening,
but I don't have any idea how to modify this so that I can reference
the textbox based on the integer value of the loop, which is
imperative to this working as intended.

I've searched this board on this question and can't find a post that
resolves this question. At least not one the I understand well enough
to adapt to my application. Can anybody help?

Thanks,
Randy
 
G

Guest

Randy,

You can supply the textbox's name as a key to the form's Controls
collection. For example:

CType (Me.Controls("tbItem" & intItemCount), TextBox).Text

But you also need to dynamically create the parameter place holders in the
Insert statement and the Parameters collection.

Kerry Moorman
 
H

Herfried K. Wagner [MVP]

Kerry Moorman said:
You can supply the textbox's name as a key to the form's Controls
collection. For example:

CType (Me.Controls("tbItem" & intItemCount), TextBox).Text

But you also need to dynamically create the parameter place holders in the
Insert statement and the Parameters collection.

However, note that this will only work if the controls are placed on the
form directly. Otherwise you'll have to use the 'Controls' collection of
the container the control belongs to.
 
R

Randy

Thanks everybody. Kerry's suggestion worked perfectly. Thanks for
the qualification, Herfried. All the controls are directly on the
form, so I didn't have to deal with that issue. As for dynamically
creating the parameter place holders, I simply added a
parameters.clear statement each time through the loop, which allowed
me to reuse the parameters without creating new ones.

Randy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top