6167

“Unable to cast object” while looping through programatically created textboxes

Question:

I have some Textboxes that are created dynamically --

int i = 1; while (reader.Read()) { System.Web.UI.WebControls.TextBox textBox = new System.Web.UI.WebControls.TextBox(); textBox.ID = reader["field_id"].ToString(); textBox.Enabled = false; HtmlGenericControl div = new HtmlGenericControl("div"); if(i%2 != 0) div.Attributes.Add("style", "margin-right:120px;padding-bottom:20px;"); if (i % 2 == 0) div.Attributes.Add("style", "padding-bottom:20px;"); div.Attributes.Add("class", "inline fourcol"); div.InnerHtml = "<label>" + reader["field"] + "</label>"; div.Controls.Add(textBox); panelId.Controls.Add(div); textBox.Text = reader["field_value"].ToString(); ++i; }

That works fine (at least i'm sure -they show up how they should). But when i try to loop through them to enable them, or get their values, i get an "<strong>Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'.</strong> " error.

This is how i've been trying to do it --

public void EditPanel(System.Web.UI.WebControls.Panel panel) { foreach (System.Web.UI.WebControls.TextBox t in panel.Controls) { t.Enabled = true; } }

Thanks!

Answer1:

You are putting each textbox inside a "div" control which is HtmlGenericControl, then inside the panel control. So first you must search for the HtmlGenericControl inside panelId.Controls

A sample code that might help you:

public void EditPanel(System.Web.UI.WebControls.Panel panel) { foreach (Control c in panelId.Controls) { if (c is HtmlGenericControl) { foreach (var textbox in c.Controls.OfType<TextBox>()) //ofType returns IEnumerable<TextBox> textbox.Enabled = true; } } }

Answer2:

You're looping over panel.Controls, which will loop over every control in the panel. This is not necessarily the same thing as looping over everything you've added. If there was something else inside the panel that existed when you started, you will end up getting that too.

What you probably wanted was this:

foreach (var t in panel.Controls.OfType<System.Web.UI.WebControls.TextBox>()) { t.Enabled = true; }

Answer3:

There is a control inside your Panel, that is not a TextBox and could not be cast to it. You should place a breakpoint before the loop and check the panel.Control collection contents in debug mode.

You can avoid the issue if you don't specify a type in the foreach loop and do the safe cast yourself.

foreach (var t in panel.Controls) { var textbox = t as System.Web.UI.WebControls.TextBox; if(textbox != null) { textbox.Enabled = true; } }

Answer4:

You should check if control is TextBox

public void EditPanel(System.Web.UI.WebControls.Panel panel) { foreach (var t in panel.Controls) { if (t is System.Web.UI.WebControls.TextBox) ((System.Web.UI.WebControls.TextBox)t).Enabled = true; } }

Answer5:

The Controls collection will contain a collection of all the controls in the panel - not just TextBoxes. You can iterate through all of the controls and use the as operator to perform a type cast. If the type cast succeeds then you may enable the textbox.

public void EditPanel(System.Web.UI.WebControls.Panel panel) { foreach (var control t in panel.Controls) { System.Web.UI.WebControls.TextBox textBox = control as System.Web.UI.WebControls.TextBox; if (textBox != null) { control.Enabled = true; } } }

Answer6:

you add the textbox to the div element and the div element to the panel. therefore you need to select the controls in the panel and then find the textbox.

foreach (var t in panel.Controls.Cast<Control>().SelectMany(c => c.Controls)) { if (t is TextBox == false) continue; ((TextBox)t).Enabled = true; }

Recommend

  • Bootstrap Accordian active state doesnt work and none of the panels are collapsed
  • Asyncronously Load Panels using jQuery in ASP.NET application
  • css Star-rating html
  • How to align an image side by side with a heading element?
  • WPF version of .ScaleControl?
  • order post according to custom array position
  • Overlapping controls in Windows XP
  • xcode don't localize specific strings
  • IE7 and TinyMCE with Plone
  • Swift: Switch statement fallthrough behavior
  • Avoid links criss cross / overlap in d3.js using force layout
  • Retrieving value from sql ExecuteScalar()
  • java.lang.NoClassDefFoundError: com.parse.Parse$Configuration$Builder on below Lollipop versions
  • What is the “return” in scheme?
  • MySQL WHERE-condition in procedure ignored
  • Which linear programming package should I use for high numbers of constraints and “warm starts” [clo
  • Websockets service method fails during R startup
  • Alternatives to the OPTIONAL fallback SPARQL pattern?
  • Web-crawler for facebook in python
  • How to get next/previous record number?
  • Apache 2.4 - remove | delete | uninstall
  • Unanticipated behavior
  • KeystoneJS: Relationships in Admin UI not updating
  • trying to dynamically update Highchart column chart but series undefined
  • Proper way to use connect-multiparty with express.js?
  • Hits per day in Google Big Query
  • Trying to get generic when generic is not available
  • Java static initializers and reflection
  • embed rChart in Markdown
  • How to get Windows thread pool to call class member function?
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • unknown Exception android
  • Checking variable from a different class in C#
  • costura.fody for a dll that references another dll
  • Observable and ngFor in Angular 2
  • How to Embed XSL into XML
  • UserPrincipal.Current returns apppool on IIS
  • Unable to use reactive element in my shiny app
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal