Solved

InvalidCastException Specified cast is not valid on Datagrid Update

Posted on 2004-08-14
7
2,067 Views
Last Modified: 2012-06-21
I thought I finally had the answer on how to perform updates on a datagrid.  I copied the basic procedure right from msdn at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbwlkwalkthroughusingdatagridwebcontroltoreadwritedata.asp

Here's my code on the datagrid update event:

    Private Sub DGusers_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DGusers.UpdateCommand
        'A Generic Update
        Dim CategoryDescript As String
        Dim key As String = DGusers.DataKeys(e.Item.ItemIndex).ToString()
        Dim tb As TextBox


        tb = CType(e.Item.Cells(0).Controls(0), TextBox)    <<<<<<<<<<<<<<<<<  ERROR OCCURS HERE
        col1 = tb.Text

This is the Error I get:
Specified cast is not valid.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Source Error:


Line 187:        Dim tx As String
Line 188:
Line 189:        tb = CType(e.Item.Cells(0).Controls(0), TextBox)
Line 190:        col1 = tb.Text
Line 191:
 
This was an example based right out of msdn and I am mystified.  
Has anyone been able to resolve this?  
Everything else seems to be working fine except for this.
 
Thank You!

Ted


0
Comment
Question by:tcalbaz
7 Comments
 
LVL 17

Accepted Solution

by:
AerosSaga earned 300 total points
ID: 11802634
Heres how I do it:

 Private Sub dg_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dg.ItemDataBound
        Dim DeleteItem As LinkButton
        If e.Item.ItemType = ListItemType.AlternatingItem Or e.Item.ItemType = ListItemType.Item Then
            DeleteItem = DirectCast(e.Item.FindControl("Linkbutton2"), LinkButton)
            DeleteItem.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this " & _
                "product?');")
        End If
    End Sub

Regards,

Aeros
0
 
LVL 15

Assisted Solution

by:Thogek
Thogek earned 200 total points
ID: 11802684
Using FindControl (as AerosSaga suggests) is generally safer than using Controls(0), simply because FindControl will find the control with the given name, whereas Controls(0) just grabs the first control, which you assume will be the TextBox.  But...

For example, if there's any HTML whitespace between the beginning of the cell and the TextBox, ASP.NET might render that whitespace as a LiteralControl.  In this case, Controls(0) will return a reference to the LiteralControl (which, understandably, will not cast to a TextBox type), while the TextBox gets pushed over to Controls(1).

In general, if there's a way to reference the specific item for which you're looking by name, rather than by numeric index, use the name: it's safer.
0
 
LVL 18

Expert Comment

by:DotNetLover_Baan
ID: 11803053
Hi there,  
  >>tb = CType(e.Item.Cells(0).Controls(0), TextBox)<<
Is your textBox in the very first column of the Grid ? Make sure you give the right column index.

-Baan
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 1

Author Comment

by:tcalbaz
ID: 11804960
Aerosaga,

Your solution looks interesting. So here is how I have adapted it - and the error I get:

-----------------------------------------------------------------------------------------------------
Private Sub DGusers_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DGusers.UpdateCommand

        Dim CategoryDescript As String
        Dim key As String = DGusers.DataKeys(e.Item.ItemIndex).ToString()
        Dim col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11 As String
        Dim tb As TextBox
        Dim tx As String

If e.Item.ItemType = ListItemType.EditItem Then

tb = DirectCast(e.Item.FindControl("ID"), TextBox) <<<<<<ERROR: Object reference not set to an instance of an object

col1 = tb.Text
End If

----------------------------------------------------------------------------

Any suggestions?

Thank you

Ted
0
 
LVL 1

Author Comment

by:tcalbaz
ID: 11804976
DotNetLover_Baan,

DotNetLover,
This is one of the confusing things to me.  As far as I understnad I never actually placed a text box inside of the Datagrid.  From what I understand all the cells on the grid are going into edit mode.  Could I be possibly misnaming the object as a Textbox?  If so, what should it be called?

Many Thanks

Ted




DotNetLover_Baan Wrote --------------------------------------
Hi there,  
  >>tb = CType(e.Item.Cells(0).Controls(0), TextBox)<<
Is your textBox in the very first column of the Grid ? Make sure you give the right column index.

-Baan
0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 11805265
I agree either the ordinal is off or you are confusing editable regions in the datagrid with textboxes.

Regards,

Aeros
0
 
LVL 1

Author Comment

by:tcalbaz
ID: 11806510
Thank you AerosSaga for showing me what to do.  
Thank you Thogek for showing me why I have to do it.

Ted

0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question