Watch Video
In this article I am going to explain how to delete row in Gridview using VB code.
Drag and drop GRiview controller to form and using data source bind data to Gridview.
Click on the Gridview and you can see arrow top right. When you click on arrow pop menu will display named as Gridview Tasks.
In that Gridview Task menu, you have to check the Enable Selection, and click on the Edit column. Next change the text on SelectedText as Delete. Then you can see the first column as Delete.
Next click on Gridview and go to properties and click Even icon, then you can see all events of Gridview.
From that event list go to SelectIndexChanges and double click. Then SelectIndexChanged event coding window will display and you can write the code as below
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim row As GridViewRow = GridView1.SelectedRow
txtBCode.Text = row.Cells(1).Text
txtBname.Text = row.Cells(2).Text
Dim myConnection As SqlConnection = New SqlConnection(GetConnectionString)
Dim myCommand As SqlCommand
myConnection.Open()
myCommand = New SqlCommand("DELETE Banks WHERE b_code =" & Val(txtBCode.Text), myConnection)
myCommand.CommandType = CommandType.Text
myCommand.ExecuteNonQuery()
myConnection.Close()
GridView1.DataBind()
End Sub
Creating the SQL connection string as below
Dim myConnection As SqlConnection = New SqlConnection(GetConnectionString)
GetConnectionString will com form Class1,vb Clase
Public Shared Function GetConnectionString() As String
GetConnectionString = ConfigurationManager.ConnectionStrings("SUPERMARKETConnectionString").ConnectionString
Return GetConnectionString
End Function
SUPERMARKETConnectionString is getting from Web.config file
<connectionStrings>
<add name="SUPERMARKETConnectionString" connectionString="Data Source=SERVER;Initial Catalog=SUPERMARKET;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
After getting the SQL connection string and Open the SQL connection. As the next step execute the SQL Command for Deleting Record from SQL Table, and Bind the data source again to Gridview.
Actually Gridview row not deleteing from Gridview. Record deleting from SQL Database Table record and SQL Database Table again bind with Gridview using Data source.
Run the project and you can see data with Gridview with first column as Delete. when you click on Delete link button. Selected row will delete.
Watch Video
0 comments:
Post a Comment