Click to See Complete Forum and Search --> : specified cast is not valid
adamshao
January 3rd, 2003, 10:40 PM
I have the following code segment to dynamically add a lable and textbox in an existing table oject. The first time it shows correctly. However, after some steps, it shows exception of "sepcified cast is not valid". If I add only one code (label or textbox), there will no problem. Any suggestion to solve this issue?
TableRow r = new TableRow();
TableCell c = new TableCell();
c.Width = 50;
Label_Filename = new Label();
Label_Filename.Text = "Filename:";
c.Controls.Add(Label_Filename);
r.Cells.Add(c);
TableCell c1 = new TableCell();
TextBox_Filename = new TextBox();
TextBox_Filename.Width = 140;
TextBox_Filename.Text = "*.*";
c1.Controls.Add(TextBox_Filename);
r.Cells.Add(c1);
Table1.Rows.Add(r);
TheCPUWizard
January 3rd, 2003, 10:59 PM
First suggestion is to actuall post a code segment that includes the variable declarations (or would you like us to guess?)
The second suggestion is to provide the specific line where the error occurs...
There are Guru's and there are Mind Readers; this is not CodeMindReaders.com"
mikescham
January 6th, 2003, 02:15 PM
This is happening because your viewstate is getting out of sync with the page. The viewstate is read sequentially by the asp.net framework and the framework expects control1 to be the first control in the page class, control2 to be the second etc.. So if you add items dynamically to the page at the wrong time or in the wrong order you will notice strange things start to happen.
For example if you were to dynamically add a textbox at control index 1 just before a dropdownlist control. If you don't add the textbox back on postback before the viewstate is processed, asp.net will pull the textbox's viewstate and try to apply it to the dropdownlist which is now at index 1 -- because you haven't added the textbox back to the webform yet. That is the cause of your 'casting' error.
The absolute best place to add dynamic controls to a web form is in the LoadViewState override:
protected override void LoadViewState(object state) {
base.LoadViewState(state);
Controls.Add(mycontrol);
}
This override gets called on every postback if the viewstate is enabled for the page. It is not called on first load, which is OK because on first load you can add dynamic controls to the page almost anytime before onprerender (or during). The trick is to load those same controls in the same order before the page load event fires during a postback. The problems you are encountering arise during postback.
cyberfyb
February 12th, 2003, 11:56 AM
I am happy to finally find something that talk about the problem I have since 2 days (in you know than 2 days in development is like 2 years).
Well, I understand the problem now with the explication from mikescham but I do not control this situation enough to know what to do in my case.
What I try to do is to post multiple time but with multiple alternatives which do not have always the same quantity of elements and same type of elements.
So, I post the first time after the user choose the message he want to modify. Then, he modify it and another post is proceed to go to the appropriate sub and functions to record the modifications into the database and show a confirmation message. But that's where I got my problem, the system never run the record-process because it "jam" at the beginning of the function (the second post).
I saw in the explication how to conserve the viewstate with the same controls but how to delete these controls from the viewstate when a new post append?
Here is my code for whom want to understand the logic:
<code>
Function GetMiddleColumn_m1o2()
If Not Request.QueryString("id") = "" And Request.Form("m1o2") = 1 Then
Dim t1 As New Table()
Dim t1r1 As New TableRow()
Dim t1r1c1 As New TableCell()
Dim label_test As New Label()
label_test.Text = "Maintenant dans la partie pour modifier"
t1r1c1.Controls.Add(label_test)
t1r1.Controls.Add(t1r1c1)
t1.Controls.Add(t1r1)
GetMiddleColumn_m1o2 = t1
ElseIf Not Request.QueryString("id") = "" And Not Request.Form("m1o2") = 1 Then
Dim t1 As New Table()
Dim t1r1 As New TableRow()
Dim t1r2 As New TableRow()
Dim t1r1c1 As New TableCell()
Dim t1r2c1 As New TableCell()
Dim t1r2c2 As New TableCell()
Dim titre As New Label()
Dim explication As New Label()
Dim lblMotdebienvenue_texte As New Label()
Dim t2 As New Table()
Dim t2r1 As New TableRow()
Dim t2r2 As New TableRow()
Dim t2r3 As New TableRow()
Dim t2r1c1 As New TableCell()
Dim t2r2c1 As New TableCell()
Dim t2r3c1 As New TableCell()
Dim txtMotdebienvenue As New TextBox()
Dim cbxFlagdefault As New CheckBox()
Dim bouton_modifier As New ImageButton()
Dim invisibleinput As New Literal()
titre.Text = "<p>Modification du mot de bienvenue #" & Request.QueryString("id") & "</p>"
titre.Font.Bold = True
explication.Font.Size = FontUnit.XSmall
explication.Text = "<p>Vous pouvez modifier les informations contenus dans les champs texte. Une fois que vous avez terminé vos modifications, cliquez sur le bouton ""<i>modifier</i>"" et le système enregistrera vos modifications.</p>"
bouton_modifier.ImageUrl = "/images/bouton_modifier.gif"
bouton_modifier.ToolTip = "Cliquez ici pour enregistrer vos modifications dans le système"
txtMotdebienvenue.ID = "txtMotdebienvenue"
txtMotdebienvenue.Font.Size = FontUnit.XSmall
txtMotdebienvenue.TextMode = TextBoxMode.MultiLine
txtMotdebienvenue.Rows = 10
txtMotdebienvenue.Columns = 45
txtMotdebienvenue.Text = GetMotdebienvenueDescription(Request.QueryString("id"))
cbxFlagdefault.ID = "cbxFlagtDefault"
cbxFlagdefault.Text = "Par défaut"
cbxFlagdefault.ToolTip = "Cochez si vous désirez utiliser ce mot de bienvenue en tant que celui par défaut ou décochez dans le cas contraire"
cbxFlagdefault.Font.Size = FontUnit.XSmall
If CheckIfMotdebienvenueDefault(Request.QueryString("id")) = True Then
cbxFlagdefault.Checked = True
Else
cbxFlagdefault.Checked = False
End If
t2r3c1.HorizontalAlign = HorizontalAlign.Center
invisibleinput.Text = "<input type=""hidden"" name=""m1o2"" value=""1"">"
'assemblage
t2r1c1.Controls.Add(txtMotdebienvenue)
t2r2c1.Controls.Add(cbxFlagdefault)
t2r3c1.Controls.Add(bouton_modifier)
t2r1.Controls.Add(t2r1c1)
t2r2.Controls.Add(t2r2c1)
t2r3.Controls.Add(t2r3c1)
t2.Controls.Add(t2r1)
t2.Controls.Add(t2r2)
t2.Controls.Add(t2r3)
t1r1c1.Controls.Add(invisibleinput)
t1r1c1.Controls.Add(titre)
t1r1c1.Controls.Add(explication)
t1r2c1.Controls.Add(t2)
t1r1.Controls.Add(t1r1c1)
t1r2.Controls.Add(t1r2c1)
t1.Controls.Add(t1r1)
t1.Controls.Add(t1r2)
GetMiddleColumn_m1o2 = t1
Else
Dim t1 As New Table()
Dim t1r1 As New TableRow()
Dim t1r1c1 As New TableCell()
Dim label1 As New Label()
label1.Text = "Modification d'un mot de bienvenue"
'assemblage
t1r1c1.Controls.Add(label1)
t1r1.Controls.Add(t1r1c1)
t1.Controls.Add(t1r1)
GetMiddleColumn_m1o2 = t1
End If
End Function
</code>
mikescham
February 13th, 2003, 12:16 PM
You can do what you want by keeping track of the state of the table you are modifying and loading the correct set of controls back to the table on postback. Then in page_load or in an event handler do your processing on what was submitted. At that point call tbl.Controls.Clear() and add in your new set of controls.
There is no harm in doing it this way the only trick is to add back in on postback what was there when the page went out to the client.
That being said, I would suggest a different approach. What you seem to be doing from your post is very simple. The solution of adding dynamic controls is error prone, complex, difficult to debug, and muddles up your code.
Try using static controls and toggling visibility of either the controls themselves or the rows that they are placed in. You get the same effect, its cleaner, and if the user wants to go back to the inputs to change something you have only to set the controls' visibility back to true.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.