dacaroglu
dacaroglu

Reputation: 43

c# Unable to cast object of type 'System.Windows.Forms.Label' to type 'System.Windows.Forms.TextBox'

i cant find anything to fix this error :/ im trying to 2 letter combinations(ex. aa,ba,cb) to multiplier like(aa*3=4*3 ba*2=3,5*2). my codes are;

string[] dersler = new string[9];
    double[] kredi = new double[9];
    double[] krediSonuclari = new double[9];

    double derscarp(double s1, double s2)
    {
        return s1 * s2;
    }
    private void button1_Click(object sender, EventArgs e)
    {

        int i=0;
        int j = 0;
        foreach (TextBox item in Controls)
        {
            if (item.Name.Substring(0,7)=="txtders")
            {
                dersler[i] = Convert.ToString(item.Text);
                i++;
            }
        }
        foreach (TextBox item in Controls)
        {
            if (item.Name.Substring(0, 8) == "txtkredi")
            {
                kredi[j] = Convert.ToDouble(item.Text);
                j++;
            }
        }

        double toplam =0;
        for (int k = 0; k < 9; k++)
        {

Upvotes: 3

Views: 8036

Answers (3)

dognose
dognose

Reputation: 20889

replace

foreach (TextBox item in Controls) //implicit cast.

}

with

 foreach (Control ctrl in Controls)
     if (ctrl is TextBox){
         TextBox tb = (Textbox)ctrl; //explicit cast
     }
 }

foreach does not automagically pick out the cherr... ehm... Textboxes of the Control Collection, so for every CONTROL inside the collection, that is NOT a TextBox the implicit cast will fail.

Upvotes: 2

Toon Casteele
Toon Casteele

Reputation: 2579

When you do this:

foreach (TextBox item in Controls)
{
    if (item.Name.Substring(0,7)=="txtders")
    {
        dersler[i] = Convert.ToString(item.Text);
        i++;
    }
}

you assume every control in your form is a textbox, which is probably not true. Because of that it will try to cast your Label controls as a TextBox, fail and throw an error.

Try this instead:

foreach (Control ctrl in Controls)
{
    TextBox item = ctrl as TextBox;
    if (item != null) 
    {
        if (item.Name.Substring(0,7)=="txtders")
        {
            dersler[i] = Convert.ToString(item.Text);
            i++;
        }
    }
}

Upvotes: 3

SLaks
SLaks

Reputation: 887215

foreach (TextBox item in Controls)

Controls contains some controls that aren't textboxes.
Your foreach statement tells the compiler to cast each item in the collection to TextBox, which won't work.

Instead, you can call .OfType<TextBox>(), which will return a filtered subsequence of the collection that only contains TextBox instances.

Upvotes: 20

Related Questions