update a row in datagrid

how i update a row in datagrid? i use the following codes.but didn't get output.there was an error "Object reference not set to an instance of an object"

Private Sub dg2_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles dg2.UpdateCommand

        getcon()      'function to get the connection
        Dim str As String
        str = datagrid.DataKeys(e.Item.ItemIndex)
        Dim txt As New TextBox
        Dim str1, str2 As String
        str1 = CType(e.Item.FindControl("txt"), TextBox).Text
        str2 = "update Client set ClientId= " & str1 & " where CurLocation='" & str & "'"
        Dim cmd As SqlCommand
        cmd.CommandText = str2
        cmd.Connection = con
        closecon()          'function to close the connection
        datagrid.EditItemIndex = -1
        bindgrid()
princyeliasAsked:
Who is Participating?
 
toocrazy007Commented:
Do you insert the text in the itemtemplate of datagrid and given the id as "txt". if so there is not need of created the instance of textbox in the codebehind.
check by tracing weather you are getting the right values into the strings str and str1.
0
 
nayernaguibCommented:
Replace the statement

        Dim cmd As SqlCommand

with

        Dim cmd As New SqlCommand

You should also add the statement

        cmd.ExecuteNonQuery()

after setting the command properties. This will execute the command against the database. Note that the connection *must* be open before executing the command.

_______________

  Nayer Naguib
0
 
princyeliasAuthor Commented:
i tried the codes.but i didn't get answer.an error occured in  
str1 = CType(e.Item.FindControl("txt"), TextBox).Text
unable to find the textbox.Is there any need to create a textbox in the HTML(code behind)

the code i'm using:

Private Sub datagrid_UpdateCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles datagrid.UpdateCommand

        getcon()       'function to get the connection
        Dim str, str1, str2  As String
        Dim txt As New TextBox
        Dim dr As SqlDataReader
        str = datagrid.DataKeys(e.Item.ItemIndex)
        str1 = CType(e.Item.FindControl("txt"), TextBox).Text
        str2 = "update Client set ClientId= " & str1 & " where CurLocation='" & str & "'"
        Dim cmd As New SqlCommand
        cmd.CommandText = str2
        cmd.Connection = con
        dr = cmd.ExecuteReader
        closecon()
        dr.Close()
        datagrid.EditItemIndex = -1
        bindgrid()
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.