Search code examples
stringwinformstextboxcoding-stylecode-cleanup

How to convert a string to an object and then manipulate it in C#


To do what I intend to do, this code works for me, but I don't think it is the most appropriate or clean way to do it

public void func2(string S){
    for (int sum = 0; sum < 25; sum++){
        if (S == "textBox1"){
            textBox1.Left = sum * 5;
           }
        if (S == "textBox2"){
            textBox2.Left = sum * 5;
           }
        ...
    }
}

Instead of using such dirty code I want to use something like this (but well implemented)

public void func2(){
    for (int sum = 0; sum < 25; sum++){
        TextBox x = "textbox"+sum;
        x.Left = sum * 5;
    } 
}

Thanks for your time


Solution

  • public async void func2()
            {
                
                List<TextBox> txtBList = Enumerable.Range(1, 25).Select(i => (TextBox)this.Controls["textbox" + i.ToString()]).ToList();
                txtBList.ForEach(leftDistance);
                await Task.Delay(100);
                txtList();
    
            }
            public void leftDistance(TextBox s)
            { 
                s.Left = sum * 5;
            }