Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

GridView insert update delete without using datasource controls - Part 25

Suggested Videos 
Part 22 - Using validation controls with asp.net gridview when editing data
Part 23 - GridView insert update delete in asp.net
Part 24 - GridView insert update delete in asp.net using objectdatasource



We discussed about inserting, updating and deleting data from gridview, using sqldatasource control in Part 23. In Part 24, we discussed about achievieng the same, using ObjectDataSource control. It is also possible to perform insert, update and delete on gridview, without using datasource controls at all, and that's what we will discuss in this video. Please watch Part 23 and Part 24, before proceeding with this video. We will be modifying the example, that we used in Part 24.



1. As we don't want to use datasource controls. Please delete "ObjectDataSource1" control from the webform.

2. Delete DataSourceID="ObjectDataSource1" from GridView1. This should remove the dependency of GridVIew1 on ObjectDataSource1 control.

3. From the code behind file, delete lbInsert_Click() event handler method.

4. In the "FooterTemplate" of "EmployeeId" TemplateField, please delete OnClick="lbInsert_Click", as we no longer have this event handler method.

5. Delete "CommandField" column from GridView1
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />

6. Now, include a template field in the place of CommandField. This template field is used to display Edit, Update, Cancel and Delete link buttons. We don't want delete and cancel buttons to cause validation, so set CausesValidaion property of these buttons to false. 
<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="lbEdit" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="EditRow" ForeColor="#8C4510" runat="server">Edit</asp:LinkButton>
        <asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false">Delete</asp:LinkButton>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:LinkButton ID="lbUpdate" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="UpdateRow" ForeColor="#8C4510" runat="server">Update</asp:LinkButton>
        <asp:LinkButton ID="lbCancel" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="CancelUpdate" ForeColor="#8C4510" runat="server" CausesValidation="false">Cancel</asp:LinkButton>
    </EditItemTemplate>
</asp:TemplateField>

7. Copy and paste the following private method. This method binds employee data with gridview1 control. 
private void BindGridViewData()
{
    GridView1.DataSource = EmployeeDataAccessLayer.GetAllEmployees();
    GridView1.DataBind();
}

8. Call BindGridViewData() in Page_Load() event.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGridViewData();
    }
}

9. Finally generate GridView1_RowCommand() event handler method. Copy and Paste the following code.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "EditRow")
    {
        int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
        GridView1.EditIndex = rowIndex;
        BindGridViewData();
    }
    else if (e.CommandName == "DeleteRow")
    {
        EmployeeDataAccessLayer.DeleteEmployee(Convert.ToInt32(e.CommandArgument));
        BindGridViewData();
    }
    else if (e.CommandName == "CancelUpdate")
    {
        GridView1.EditIndex = -1;
        BindGridViewData();
    }
    else if (e.CommandName == "UpdateRow")
    {
        int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;

        int employeeId = Convert.ToInt32(e.CommandArgument);
        string name = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox1")).Text;
        string gender = ((DropDownList)GridView1.Rows[rowIndex].FindControl("DropDownList1")).SelectedValue;
        string city = ((TextBox)GridView1.Rows[rowIndex].FindControl("TextBox3")).Text;

        EmployeeDataAccessLayer.UpdateEmployee(employeeId, name, gender, city);
                
        GridView1.EditIndex = -1;
        BindGridViewData();
    }
    else if (e.CommandName == "InsertRow")
    {
        string name = ((TextBox)GridView1.FooterRow.FindControl("txtName")).Text;
        string gender = ((DropDownList)GridView1.FooterRow.FindControl("ddlGender")).SelectedValue;
        string city = ((TextBox)GridView1.FooterRow.FindControl("txtCity")).Text;

        EmployeeDataAccessLayer.InsertEmployee(name, gender, city);
                
        BindGridViewData();
    }
}

10. In the FooterTemplate of EmployeeId TemplateField, set CommandName property lbInsert link button to "InsertRow"
<asp:LinkButton ID="lbInsert" CommandName="InsertRow" ForeColor="#8C4510"  ValidationGroup="Insert" runat="server">Insert</asp:LinkButton> 


11. If you want to show a confirmation dialog box, before a row is deleted, include javascript confirm() function, using "OnClientClick" attribute of LinkButton "lbDelete".
<asp:LinkButton ID="lbDelete" CommandArgument='<%# Eval("EmployeeId") %>' CommandName="DeleteRow" ForeColor="#8C4510" runat="server" CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this row');">Delete</asp:LinkButton>

12 comments:

  1. I like your video but I have another problem I want deploy windows application (c sharp application) which have database.How we can deploy windows application with .mdf database and how we can insert multiple
    product key during deployment and how can insert .net framework to install that program or software on another machine which don't have .net framework.In short how can develop windows base software which is installed another computer. send me +ve or -ve reply on desaimandar2@gmail.com

    ReplyDelete
  2. Hai venkat,

    your videos are just awesome.It's really helping everyone to know the concepts very clearly.

    Can you please clarify my doubt.What is the difference between Eval and Bind in gridview?

    ReplyDelete
    Replies
    1. Hi Arjunan, This is a very good question. Thanks for asking.

      Eval is one-way, read only databinding.

      Bind is two-way, read/write databinding.

      Bind, enables to save the changed values back to the database.

      Delete
  3. love your lessons they are a great help, thanks a lot for taking the time to spread the knowledge :).
    Rasha.

    ReplyDelete
  4. Hi There
    You are doing great job.Would that be possibility the insert row will appear at the top of the grid instead at the bottom of the grid. If you have dataset which might have 1000 of rows it will be difficult for user to insert the row at the end of the grid
    I tried to put insert row on the header template instead of footer template then my column name disappear
    Can you please reply it is really urgent?
    Thanks
    Qazafi

    ReplyDelete
    Replies
    1. Hi, I haven't done this myself. I think the approach you have taken should work, except for the headers. For headers may be use HTML table with just one row, and use CSS styles to make it look as if it is a header that belong to the gridview. I will research on this further and will let you know, if I find a better way. Good Luck.

      Delete
  5. Hi Venkat
    Thanks a ton for your valuable suggestion. I will try it and let you know as soon as possible. Your videos are valuable source of info.
    I have another question I have a requirement to embed the calendar control inside the Grid view control. The problem is when I used normal calendar control inside the Grid view it take lot of space and the grid column height take lot of space. Would that be possibility when we click inside a textbox of grid view control, it will pop-up calendar control. And put value inside the textbox
    I will really appreciate your response in this regard.
    Keep the good work please.
    Many thanks
    Qazafi

    ReplyDelete
  6. hi venkat.. how did u create this page for comment. and the replie too? and how to we send command from textbox without using a button?

    ReplyDelete
  7. Hi Venkat
    I have a problem. I am having a gridview which is displaying data from 5 different stored procedures. I need to edit 5 columns in the displayed data and update them into their respective tables. For ex-data from employee, manager and state tables is being displayed, i.e. employeeid,name,salary,mangerid,mangername,statename columns are being displayed and only name columns,salary and statename columns should be editable and then updated back into their respective tables.
    How to achieve this directly in gridview?

    ReplyDelete
  8. Hi sir, my self Zeal Nagar.
    following is rough code.
    in updaterow
    textbox1 returning old value rather then new value.
    so please help me to solve this problem

    else if (e.CommandName == "UpdateRow")
    {
    int rowindex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
    int id = Convert.ToInt32(e.CommandArgument);
    TextBox txtbqt = (TextBox)GridView1.Rows[rowindex].FindControl("TextBox1");
    int total = 0;
    int qt = int.Parse(txtbqt.Text);
    conn = MyConnections.ConnectDB();
    conn.Open();
    try
    {
    cmd = conn.CreateCommand();
    cmd.CommandText = "select Price from items where ItemNo="+id;
    mdr = cmd.ExecuteReader();
    if (mdr.Read())
    {
    total = qt * mdr.GetInt32(0);
    }
    mdr.Close();
    cmd = conn.CreateCommand();
    cmd.CommandText = "update addtocart set Quantity=" + qt + ", TotalPrice=" + total +" where Email='"+Session["User"]+"' and ItemNo="+id;
    cmd.ExecuteNonQuery();
    conn.Close();
    GridView1.EditIndex = -1;
    BindData();
    }
    catch (Exception e1)
    {
    Response.Write(e1.ToString());
    }
    }

    ReplyDelete
  9. Hello Venkat Sir
    I am big fan of your video tutorials
    sir i have a question ?
    sir how i create a grid view which show the search button output and having all function like update and delete ?
    Please help

    ReplyDelete

It would be great if you can help share these free resources