Question: Invalid Cast Exception Error

  • Thread starter Thread starter VB Programmer
  • Start date Start date
V

VB Programmer

I have code that changes the bkground color of the webform on page_load.
Here it is:
Dim Body As New HtmlGenericControl
Body = CType(Page.Controls(1), HtmlGenericControl)
Body.Attributes("bgcolor") =
ConfigurationSettings.AppSettings("BackgroundColor")

I'm getting this error message "System.InvalidCastException: Specified cast
is not valid." at this line:
Body = CType(Page.Controls(1), HtmlGenericControl)

But, because Option Strict is On I have to cast it (no implicit
conversions).

Any ideas?

Thanks!
 
What control is currently placed on the Form in position 2 (Controls is 0
based)? If nothing, you are going about this the wrong way. If something,
you may have a control that is incompatible with HtmlGenericControl. Without
seeing the rest of the code, I can only continue guessing.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

**********************************************************************
Think Outside the Box!
**********************************************************************
 
I followed the example I saw for dynamically changing the bckground color.
Is there a better way to change the background color of the form
dynamically? Or, is there a way to specifically reference the "Page"
control?
 
FYI:

This is what that control is...
? page.controls(1)
{System.Web.UI.HtmlControls.HtmlForm}
[System.Web.UI.HtmlControls.HtmlForm]:
{System.Web.UI.HtmlControls.HtmlForm}
BindingContainer: {ASP.OfficeViewAc_aspx}
ClientID: "Form1"
Controls: {System.Web.UI.ControlCollection}
EnableViewState: True
ID: "Form1"
NamingContainer: {ASP.OfficeViewAc_aspx}
Page: {ASP.OfficeViewAc_aspx}
Parent: {ASP.OfficeViewAc_aspx}
Site: Nothing
TemplateSourceDirectory: "/POWERWeb"
UniqueID: "Form1"
Visible: True
 
Never mind. When I added "runat="server"" to the BODY tag it worked!

VB Programmer said:
FYI:

This is what that control is...
? page.controls(1)
{System.Web.UI.HtmlControls.HtmlForm}
[System.Web.UI.HtmlControls.HtmlForm]:
{System.Web.UI.HtmlControls.HtmlForm}
BindingContainer: {ASP.OfficeViewAc_aspx}
ClientID: "Form1"
Controls: {System.Web.UI.ControlCollection}
EnableViewState: True
ID: "Form1"
NamingContainer: {ASP.OfficeViewAc_aspx}
Page: {ASP.OfficeViewAc_aspx}
Parent: {ASP.OfficeViewAc_aspx}
Site: Nothing
TemplateSourceDirectory: "/POWERWeb"
UniqueID: "Form1"
Visible: True

Cowboy (Gregory A. Beamer) said:
What control is currently placed on the Form in position 2 (Controls is 0
based)? If nothing, you are going about this the wrong way. If something,
you may have a control that is incompatible with HtmlGenericControl. Without
seeing the rest of the code, I can only continue guessing.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

**********************************************************************
Think Outside the Box!
**********************************************************************
 
Back
Top