textbox names equal to variables

G

Guest

Hi,

Simple question... I have a form with 3 textboxes : txt1, txt2,txt3

I have the names of those 3 textboxes stored in a db with their
cooresponding values.
txt1 , "test1"
txt2, "test2"
txt3, "test3"

My question is if I pull the 1st entry from the db, I read 'txt1' into a
variable 'x'. How do I then say x.text = "whatever" (so that I'm really
saying txt1.text = "whatever") I hope this makes sense and isn't too simple
of a question.
 
M

Morten Wennevik

Hi ar,

Well, you could loop through all your TextBoxes and grab the one you need.
Beware that the reference name cannot be used so you will have to store
'txt1' etc in either the Control.Name property or Control.Tag

string s = "txt1";
string t = "test1";
TextBox tb = null;
foreach(Control c in this.Controls)
{
if(c.Name == s)
tb = (TextBox)c;
}

tb.Text = t;
 
G

Guest

Hi Morten,

Thanks for the reply. For some reason when I run the code, I get 'Name' is
not a member of 'System.Web.UI.Control'

Any ideas? I know it's something simple....
 
M

Morten Wennevik

Well, you didn't specify web so I thought you meant Windows controls.
There is no Name or Tag property in the Web controls.

You may be able to overcome this by keeping the references in an array
along with their names, or something like that.

struct Item
{
public TextBox tb;
public string Name;
public Item(TextBox t, string s)
{
tb = t;
Name = s;
}
}

ArrayList list = new ArrayList()
list.Add(new Item(txt1, "txt1");
list.Add(new Item(txt2, "txt2");
list.Add(new Item(txt3, "txt3");

foreach(Item i in list)
{
if(i.Name == "txt1")
{
i.tb.Text = "test1";
break;
}
}

PS! code is not tested
 
C

Cor Ligthert

Ar,

Are you using VBNet or C#?
(Than I can make a little sample how to catch this easy).

Cor
 
C

Cor Ligthert

ar,

This little (tested) sample needs on a webpage three textboxes with ID
Test1, Test2, Test3

\\\
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim frm As Control = Me.FindControl("Form1")
Dim test() As String = {"Whatever1", "Whatever2", "Whatever3"}
For Each ctr As Control In frm.Controls
If Not ctr.ID Is Nothing Then
If ctr.ID.Substring(0, 4) = "Test" Then
DirectCast(ctr, TextBox).Text = _
test(CInt(ctr.ID.Substring(4, 1)) - 1)
End If
End If
Next
End Sub
///
I hope this helps?

Cor
 

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