Solved

InvalidCastException Specified cast is not valid on Datagrid Update

Posted on 2004-08-14
7
2,062 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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

747 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

11 Experts available now in Live!

Get 1:1 Help Now