Tutorial RSS
 
Navigator: Home - Advanced - Add/Edit/Delete Access DB, using ADO.NET + DataGrid C#

Add/Edit/Delete Access DB, using ADO.NET + DataGrid C#

Learn how to display data from an Access Database using ADO.NET and a DataGrid, and also learn how we can use the DataGrid to add new data and edit & delete existing data. C# version.

Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.



In this tutorial, we will show how we can display data from an Access database in a DataGrid Control, using ADO.NET. We will also see how we can use the DataGrid to edit, delete and add records to the database. First, we start off by adding the DataGrid to our ASPX page:
Note: All the On<Event>Commands will be referenced in our code.
<form id="form1" runat="server">
<div>
<asp:DataGrid ID="DataGrid1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyField="ID" ForeColor="#333333" GridLines="None" OnCancelCommand="DataGrid1_CancelCommand" OnDeleteCommand="DataGrid1_DeleteCommand" OnEditCommand="DataGrid1_EditCommand" OnUpdateCommand="DataGrid1_UpdateCommand">
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditItemStyle BackColor="#2461BF" />
<SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:EditCommandColumn CancelText="Cancel" EditText="Edit" UpdateText="Update"></asp:EditCommandColumn>
<asp:BoundColumn DataField="PetName" HeaderText="Pet Name"></asp:BoundColumn>
<asp:BoundColumn DataField="PetType" HeaderText="Pet Type"></asp:BoundColumn>
<asp:ButtonColumn CommandName="Delete" Text="Delete"></asp:ButtonColumn>
</Columns>
</asp:DataGrid>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add" /></div>
</form>

Next, we add the code to read the data from the database:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
ReadRecords();
}

private void ReadRecords()
{
OleDbConnection conn = null;
OleDbDataReader reader = null;
try
{
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("db/Database1.mdb"));
conn.Open();

OleDbCommand cmd =
new OleDbCommand("Select * FROM Table1", conn);
reader = cmd.ExecuteReader();

DataGrid1.DataSource = reader;
DataGrid1.DataBind();
}
finally
{
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
}

Need help with Windows Dedicated Hosting? Try Server Intellect. I'm a happy customer!


The above piece of code simply reads the data from the database and binds it to the DataGrid. We can now add more functionality to the DataGrid by adding the Button Columns Add, Update and Cancel, as well as Delete. We do this by going into the Property Builder (Property Pages) and choosing these buttons from the Button Column list. First, we uncheck 'Creat columns automatically at run time, and then we also add a Bound Column for each database column we want displayed by the DataGrid. For each of these Bound Column, we type the Header Text and the Data Field should correspond with the column ID in the Access database.
Once we have done this, we can add the code to edit and update the fields:

protected void DataGrid1_CancelCommand(object source, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
ReadRecords();
}

protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = e.Item.ItemIndex;
ReadRecords();
}

protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
int ID = (int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];

string name = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
string type = ((TextBox)e.Item.Cells[2].Controls[0]).Text;

string sql =
"UPDATE Table1 SET PetName=\"" + name +
"\", PetType=\"" + type + "\"" +
" WHERE ID=" + ID;
ExecuteNonQuery(sql);

DataGrid1.EditItemIndex = -1;
ReadRecords();
}

private void ExecuteNonQuery(string sql)
{
OleDbConnection conn = null;
try
{
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("db/Database1.mdb"));
conn.Open();

OleDbCommand cmd =
new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
}
finally
{
if (conn != null) conn.Close();
}
}

The entire code-behind will look something like this:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
ReadRecords();
}

private void ReadRecords()
{
OleDbConnection conn = null;
OleDbDataReader reader = null;
try
{
conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("db/Database1.mdb"));
conn.Open();

OleDbCommand cmd =
new OleDbCommand("Select * FROM Table1", conn);
reader = cmd.ExecuteReader();

DataGrid1.DataSource = reader;
DataGrid1.DataBind();
}
finally
{
if (reader != null) reader.Close();
if (conn != null) conn.Close();
}
}

protected void DataGrid1_CancelCommand(object source, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = -1;
ReadRecords();
}

protected void DataGrid1_EditCommand(object source, DataGridCommandEventArgs e)
{
DataGrid1.EditItemIndex = e.Item.ItemIndex;
ReadRecords();
}

protected void DataGrid1_UpdateCommand(object source, DataGridCommandEventArgs e)
{
int ID = (int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];

string name = ((TextBox)e.Item.Cells[1].Controls[0]).Text;
string type = ((TextBox)e.Item.Cells[2].Controls[0]).Text;

string sql =
"UPDATE Table1 SET PetName=\"" + name +
"\", PetType=\"" + type + "\"" +
" WHERE ID=" + ID;
ExecuteNonQuery(sql);

DataGrid1.EditItemIndex = -1;
ReadRecords();
}

private void ExecuteNonQuery(string sql)
{
OleDbConnection conn = null;
try
{
conn = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("db/Database1.mdb"));
conn.Open();

OleDbCommand cmd =
new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
}
finally
{
if (conn != null) conn.Close();
}
}

protected void Button1_Click(object sender, EventArgs e)
{
string sql = "INSERT INTO Table1 (PetName, PetType)"
+ " VALUES (\"new\", \"new\")";
ExecuteNonQuery(sql);
ReadRecords();
}

protected void DataGrid1_DeleteCommand(object source, DataGridCommandEventArgs e)
{
int ID = (int)DataGrid1.DataKeys[(int)e.Item.ItemIndex];

string sql = "DELETE FROM Table1 WHERE ID=" + ID;
ExecuteNonQuery(sql);
ReadRecords();
}
}



Looking for the VB.NET 2005 Version? Click Here!

Looking for more ASP.NET Tutorials? Click Here!

Try Server Intellect for Windows Server Hosting. Quality and Quantity!


Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!

411asp.net123aspxDotNetFreaksServer Intellect