How To Delete GridView's Row Using Microsoft Access
Here we are binding a GridView from MicroSoft Office Access in Asp.Net. I create a table tblStudent in Access which is containing students information like Name, Branch and City. We are deleting one by one row from GridView.
Points Of Remember:
1. Fire GridView's RowDeleting event.
2. Set GridView's AutoGenerateDeleteButton propery to True
3. Set GridView's DataKeyNames Property to record ID (ID=Primary/Unique key of student table)
4. Add namespace System.Data and System.Data.OleDb in your C# page.
<head runat="server">
<title>GridView with Access</title>
<link href="../../Css/GridView.css" rel="stylesheet" />
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CssClass="GridViewStyle" Width="710px"
DataKeyNames="ID" OnRowDeleting="GridView1_RowDeleting"
AutoGenerateDeleteButton="True" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Branch" HeaderText="Branch" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
<HeaderStyle CssClass="HeaderStyle" />
<RowStyle CssClass="RowStyle" />
<AlternatingRowStyle CssClass="AlternatingRowStyle" />
</asp:GridView>
</div>
</form>
</body>
</html>
In above example, I simply used a GridView.css for look and feel, for more about GridView cssClass visit GridView Style article.
C# Codes :
using System.Data;
using System.Data.OleDb;
public partial class GridView_test_GridView_Access
:
System.Web.UI.
Page
{
OleDbConnection con= new OleDbConnection(@"Provider=Microsoft.JET.OLEDB.4.0;
Data Source=E:\programidea Demo\DbStudent.mdb; Persist Security Info=False;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
// Bind GridView
protected void BindGridView()
{
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(
"select
* from tblStudent"
, con);
con.Open();
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
// Delete GridView's Row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
// Retrieve row-id which is deleting
string id = GridView1.DataKeys[e.RowIndex].Value.ToString();
OleDbCommand cmd = new OleDbCommand(
"Delete
from tblStudent where ID="
+ id, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
// Refresh the GridView
BindGridView();
}