v3z3t4
v3z3t4

Reputation: 65

How to store textboxes into an array during runtime

The Situation is like this: I have multiple textboxes. On the occurrence of textChanged event the textbox should be stored in the array so that I can use it in further functions.

private void txt_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox t;
        t = (TextBox)sender;
    }

Now I have the textbox which was responsible for the event. Now I have to store this and more to come in an array so that these can be accessed elsewhere in another function.

Upvotes: 1

Views: 1370

Answers (3)

david.s
david.s

Reputation: 11403

Assuming you want to store the text from the TextBoxes, you can use a dictionary like this:

private Dictionary<string, string> dictionary = new Dictionary<string, string>();

private void txt_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    string key = textBox.Name;
    string value = textBox.Text;
    if (!dictionary.ContainsKey(key))
    {
        dictionary.Add(key, value);
    }
    else
    {
        dictionary[key] = value;
    }
}

Upvotes: 0

dknaack
dknaack

Reputation: 60438

Description

I dont know why you need to store your TextBoxes in a List or Array but you can use the generic List for that.

Represents a strongly typed list of objects that can be accessed by index. Provides methods to search, sort, and manipulate lists.

Sample

List<TextBox> myTextBoxes = new List<TextBox>();
// Add a TextBox
myTextBoxes.Add(myTextBox);
// get a TextBox by Name
TextBox t = myTextBoxes.Where(x => x.Name == "TextBoxName").FirstOrDefault();

More Information

Upvotes: 1

ramsey_tm
ramsey_tm

Reputation: 792

You could throw it in a list if ya like. Not sure why you would really want to do this though...

List<TextBox> txtbxList = new List<TextBox>();

private void txt_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox t;
        t = (TextBox)sender;
        txtbxList.Add(t);
    }

Upvotes: 4

Related Questions