Link to home
Start Free TrialLog in
Avatar of princyelias
princyelias

asked on

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()
Avatar of nayernaguib
nayernaguib
Flag of Egypt image

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
Avatar of princyelias
princyelias

ASKER

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()
ASKER CERTIFIED SOLUTION
Avatar of toocrazy007
toocrazy007

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial