Dynamically get a control name/value in loop

Alexandru Teodor 91 Reputation points
2022-06-30T11:52:45.133+00:00

Hello,

In a VS2019 WindowsFormsApp, using C#, I got 10 TextBox inputs (named input_1, input_2 ... input_10).
I am trying to get create a loop and get the values of each control.

How can I dynamicaly generate the control name, to get the values in a loop (something like: string value = input_[i].Text)?

I tried the following:

var input_ = new Control[10];  
for (int i = 0; i < input_.Length; i++)  
{  
    MessageBox.Show(input_[i].Text); // <-- System.NullReferenceException: 'Object reference not set to an instance of an object.'  
}  

Thanks.

EDIT: I am looking to find out if there is a way to do it without setting up a list first like:

var textBoxs = new List<TextBox> { input_1, input_2, .............. input_x};  
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    2022-06-30T13:08:44.267+00:00

    I put together a sample that may seem like overkill but once you think about it you should see it has value passed this question. For instance, as in the screenshot, the extension method TextBoxList find all TextBox controls even in other controls such as panels and group boxes and they can be nested. Otherwise see this post.

    listBox1.DataSource = this.TextBoxList()  
        .Select(x => new TextBoxItem(x.Name, x.Text)).ToList();  
    

    Edit to sort TextBoxes by name accounting for say TextBox1, TextBox10 etc which will not sort properly without help

    List<TextBoxItem> textBoxes = this.TextBoxList()  
        .Select(x => new TextBoxItem(x.Name, x.Text))  
        .OrderBy(x => Regex.Match(x.Name, @"\d+").Value,   
            new SemiNumericComparer())  
        .ToList();  
    listBox1.DataSource = textBoxes;  
    

    Full source found here

    Simplistic version

    private List<TextBox> _textBoxes;  
    private void GetAllButtons_Click(object sender, EventArgs e)  
    {  
        _textBoxes = this.TextBoxList();  
    }  
    

    216592-screenshot.png

    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Jack J Jun 25,316 Reputation points
    2022-07-01T02:43:18.32+00:00

    @Alexandru Teodor , Welcome to Microsoft q&a, you could try the following code to get get a control name/value in loop.

    Code example:

     private void button1_Click(object sender, EventArgs e)  
            {  
                List<TextBox> list=this.Controls.Cast<Control>().Where(i=>i.GetType() == typeof(TextBox)).Cast<TextBox>().ToList();  
                foreach (TextBox tb in list)  
                {  
                    listBox1.Items.Add(tb.Name+"**"+tb.Text);  
                }  
                  
            }  
    

    Tested result:

    216801-image.png

    Hope this could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

  2. Bruce (SqlWork.com) 81,981 Reputation points Volunteer Moderator
    2022-06-30T14:59:47.387+00:00

    Your code only allocated the control array, with each entry null. You need to create the controls and set each array entry to a value.

    0 comments No comments

  3. Alexandru Teodor 91 Reputation points
    2022-07-01T04:51:58.777+00:00

    Thank you all for your answers. Both answers helped me understand more then I asked which is great.
    If I could I would accept more then one answer :)

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.