Question

I have a gridview which contains buttons of delete and edit the row. I have this html code for the gridview:

<asp:GridView ID="gvList" runat="server">
<Columns>

<asp:TemplateField HeaderText="Actions" HeaderStyle-ForeColor="black" HeaderStyle-Font-Bold="true">
<ItemTemplate>
<asp:Button ID="btnedit" runat="server" Text="Edit" />
<asp:Button CommandArgument='<%# Eval("cUserName")%>' ID="btnDelete" OnClick="DeleteRow" runat="server" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

I need to activate the delete and the edit buttons using commandargument. I dont have the full understand of commandargument and i guess there is other ways to do this better. anyway, i have this code in vb server side:

Public Function DelRow() As DataTable

Dim Btn As ImageButton = CType(sender, ImageButton)


    Dim Query As String = "Delete FROM Intranet.dbo.Gn_ISCoordinators where cUserName=" & Btn.CommandArgument
    Dim dt As DataTable = New DataTable()
'
'I need to complete this
'...
'
End Using
End Function

In addition, i want to know if the btnAdd.CommandArgument is correct or not. Ps: I have error in CType(sender, ImageButton) under sender.

No correct solution

OTHER TIPS

asp:Button should be cast using following line:

Dim Btn As ImageButton = CType(sender, Button)

As Button not as ImageButton.

Secondly, you will get user name from Btn.CommandArgument but concatenating CommandArgument with SQL query is not a very nice idea. If not stored procedures or some ORM framework at least try using query with parameters. Use the following to connect to database and execute query:

Using con As SqlConnection = New SqlConnection(<CONNECTION_STRING>)
    con.Open()
    Dim sql As String = "Delete FROM Intranet.dbo.Gn_ISCoordinators where" & _
                      " cUserName= @UserName"

    Dim cmd As SqlCommand = New SqlCommand(sql, con)
    cmd.Parameters.Add(New SqlParameter("@UserName", Btn.CommandArgument))

    cmd.ExecuteNonQuery() 
    con.Close()
End Using

PS:- My VB.Net is at best rustic. Also please take care that you might get exception when executing code against database. So please use exception handling etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top