Hi Joey,
Please refer the below code.
Database
CREATE TABLE [Vegetables](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[PricePerKg] [varchar](50) NULL,
[Quantity] [int] NULL,
CONSTRAINT [PK_Vegetables] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
HTML
<asp:GridView ID="gvVegetables" runat="server" AutoGenerateColumns="false" OnSelectedIndexChanged="OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="PricePerKg" HeaderText="PricePerkg" />
<asp:ButtonField Text="Select" CommandName="Select" />
</Columns>
</asp:GridView>
<br />
<table>
<tr>
<td>Id:</td>
<td>
<asp:Label ID="lblId" runat="server"></asp:Label></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button Text="Delete" runat="server" OnClick="OnDelete" /></td>
</tr>
</table>
Namespace
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
Code
#region Events
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
protected void OnDelete(object senedr, EventArgs e)
{
int id= Int32.Parse(lblId.Text);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(constr))
{
using (SqlCommand sqlCommand = new SqlCommand("DELETE Vegetables WHERE Id = @Id ", sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@Id", id);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
}
this.BindGrid();
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
int id = int.Parse(gvVegetables.SelectedRow.Cells[0].Text);
lblId.Text = id.ToString();
}
#endregion
#region Private Methods
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection sqlConnection = new SqlConnection(constr))
{
using (SqlCommand sqlCommand = new SqlCommand("SELECT TOP 20 Id, Name, PricePerKg FROM Vegetables", sqlConnection))
{
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
using (DataTable dtVegetables = new DataTable())
{
sqlDataAdapter.Fill(dtVegetables);
gvVegetables.DataSource = dtVegetables;
gvVegetables.DataBind();
}
}
}
}
}
#endregion
Screenshot
