Solved

InvalidCastException Specified cast is not valid on Datagrid Update

Posted on 2004-08-14
7
2,066 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Editing XSL files, 2 43
Sending E-mail ASP.Net 3 56
Re-position sub-options beneath the TAB 7 77
Entity Framework 7 32
In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
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…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

896 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now