Pages

Aug 10, 2010

Simple Add,Edit,Update and Delete operations in GridView + Asp.net 3.5

Lets first create a table in MSAccess like below named Customer

Customer Table















Aspx Page:

Drag a gridview and fields and event as given below


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
                DataKeyNames="ID" onrowcommand="GridView1_RowCommand"
                onrowdeleting="GridView1_RowDeleting"
                onrowediting="GridView1_RowEditing"
                onrowdatabound="GridView1_RowDataBound"
                onrowupdating="GridView1_RowUpdating">
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true"/>
                    <asp:TemplateField HeaderText="Name">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtTName" runat="server"
                             Text='<%# Bind("Name") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'>
                            </asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Age">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtTAge" runat="server"
                            Text='<%# Bind("Age") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Age") %>'>
                           </asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowDeleteButton="True" />
                    <asp:CommandField ShowEditButton="True" />
                </Columns>
            </asp:GridView>

.cs page:
// Create a connection to Access Database.
OleDbConnection aConnection = new OleDbConnection
 ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\CustomerInfo.mdb");

// Binds grid on page load.

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


// Method to bind grid

private void bindGrid()
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        OleDbDataAdapter adap = null;
        DataSet ds = new DataSet();
        try
        {
            aConnection.Open();
            query = "SELECT * FROM Customer";
            cmd = new OleDbCommand(query, aConnection);
            adap = new OleDbDataAdapter(cmd);
            adap.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
        catch (Exception)
        {
          
            throw;
        }
        finally
        {
            aConnection.Close();
        }

// To make the grid editable when edit button clicked

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bindGrid();
    }

// Performs Delete and Update operations

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int cusID = 0;
        GridView gv = (GridView)sender;
       // to find the Current ID selected.
        cusID = Convert.ToInt32(
        gv.Rows[Convert.ToInt32(e.CommandArgument)].Cells[0].Text);
        if (e.CommandName == "Delete")
        {
            DeleteCustomer(cusID);
        }
        if (e.CommandName == "Update")
        {
           // to find the edit text box  value.
           TextBox txtname = GridView1.Rows[Convert.ToInt32(e.CommandArgument)]
            .FindControl("txtTName") as TextBox;
           TextBox txtage = GridView1.Rows[Convert.ToInt32(e.CommandArgument)].
            FindControl("txtTAge") as TextBox;
            updateCustomer(txtname.Text, txtage.Text, cusID);
        }
    }

//To create an Alert before deleting the row in gridview.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        foreach (Control control in e.Row.Cells[3].Controls)
        {
            LinkButton DeleteButton = control as LinkButton;
            if (DeleteButton != null && DeleteButton.Text == "Delete")
            {
                DeleteButton.OnClientClick =
                 "return(confirm('Are you sure you want to delete this record?'))";
            }
        }
    }

// Method to Delete Customer Information

private void DeleteCustomer(int ID)
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        try
        {
            query = "DELETE FROM Customer WHERE ID=" + ID;
            cmd = new OleDbCommand(query, aConnection);
            aConnection.Open();
            cmd.ExecuteNonQuery();
            aConnection.Close();
            bindGrid();
          
        }
        catch (Exception)
        {

            throw;
        }
        finally
        {
          
        }
    }

// Method to update customer with edit values.

private void updateCustomer(string name, string age, int ID)
    {
        string query = string.Empty;
        OleDbCommand cmd = null;
        try
        {
            query = "UPDATE Customer SET Name='" + name + "',Age='" +
                         age + "' WHERE ID=" + ID;
            cmd = new OleDbCommand(query, aConnection);
            aConnection.Open();
            cmd.ExecuteNonQuery();
            aConnection.Close();
            GridView1.EditIndex = -1;
            bindGrid();
        }
        catch (Exception)
        {

            throw;
        }
    }

Above given is the code used to perform Edit,Update
and delete operations in a gridview.

No comments: