getting new textbox value in for loop

DB_Fury
DB_Fury used Ask the Experts™
on
I am trying to loop through a comma delimited string. each on i want to get the value of the textbox after i click the update link in a c# datagrid. The code i have will run the first time around but when i get to 2 it stop and gives me the error:

System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.CheckBox' to type 'System.Web.UI.WebControls.TextBox'.


I know this is becuase I have to somehow change the name of the textbox from txt each time. does anyone know how to solve this problem?
for (int i = 1; i <= strArray.Length; i++)
        {
            TextBox txt =  (TextBox)row.Cells[i].Controls[0];

         
       
            Update = Update + " " + strArray[i].ToString() + "=" + txt.Text + ",";
                    
        }

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Author

Commented:
add the following line of code after setting the update string:


txt.dispose();

The error sounds like the array of Controls contains a CheckBox and you try to coerce it into a variable of type TextBox, try perhaps checking the type of the Control, something like

for (int i = 1; i <= strArray.Length; i++)
{
      if(row.Cells[i].Controls[0].GetType() == "TextBox")
      {
            TextBox txt =  (TextBox)row.Cells[i].Controls[0];

         
       
            Update = Update + " " + strArray[i].ToString() + "=" + txt.Text + ",";
      }                    
}

or if it doesn't matter if it's a Text box simply skip coercing the control into a TextBox variable and retrieve the Control's Text property as all of them should have it:


for (int i = 1; i <= strArray.Length; i++)
{
      if(row.Cells[i].Controls[0].GetType() == "TextBox")
      {
            Update = Update + " " + strArray[i].ToString() + "=" + row.Cells[i].Controls[0].Text + ",";
      }                    
}

Commented:
Your code is running on every first control of every Cell in row variable. If this variable has some different Controls like Checkbox or Ratiobutton the Exeption will raise:

Try this code:

if(row.Cells[i].Controls[0] is TextBox){
TextBox txt =  (TextBox)row.Cells[i].Controls[0];
Update = Update + " " + strArray[i].ToString() + "=" + row.Cells[i].Controls[0].Text + ",";
}

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial