问题描述:

I am designing a windows application using C#, I have created dynamically 2 Textboxes, 5 Comboboxes and 1 NumericUpDown. I want all their values to be saved in database using 3-tier architecture, but i came across a unresolved frustrating issue. I have used Control Collection so that i can go through value of each control. Am I right with this approach?. Secondly when i tried to get the value of my Textbox in a Message Box it throws an exception of "Unable to cast an object of 'System.Windows.Forms.Button' to type 'ControlCollection' My code:

ArrayList list = new ArrayList(this.Controls);

foreach (ControlCollection ctrl in list)

{

if(ctrl is TextBox)

{

MessageBox.Show(ctrl[2].Text);

}

}

网友答案:

try below tested and working sample code

    public Form1()
    {
        InitializeComponent();

        TextBox tb = new TextBox();
        tb.Name = "aa";
        tb.Text = "11";

        TextBox tb2 = new TextBox();
        tb2.Name = "bb";
        tb2.Text = "22";
        this.Controls.Add(tb);
        this.Controls.Add(tb2);

    }
    private void button1_Click(object sender, EventArgs e)
    {
        foreach (Control c in this.Controls)
        {
            if (c is TextBox)
            {
                if (c.Name.Equals("bb")) 
                    MessageBox.Show("bb value:" + c.Text);
            }
        }
    }
相关阅读:
Top