Solved

InvalidCastException Specified cast is not valid on Datagrid Update

Posted on 2004-08-14
7
2,068 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
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.

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…

828 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