CODEDIGEST
Home » Articles
Search
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Edit,Update and Delete in GridView using DataKeys

By phani
Posted On Apr 01,2009
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 0
Category: ASP.Net
Print this article.

Edit,Update and Delete in GridView using DataKeys

 

Introduction


In this article, i will discuss how to edit and delete records in gridview using datakeys.

 

What is a datakey?

A datakey represents the primary key field or field of a record that can uniquely identify it in a data-bound control. Many a times in our applications we use primary keys to get control of the particular record in the gridview. For this situation, many developers use invisible columns (Hidden columns) in the gridview to identify that row. We can achieve the same functionality using Datakeys.

Implementation
In this example, I am going to retrieve values from categories table of Northwind database. Here, we have categoryid as the primary key.

Drag a GridView into the WebForm and assign DataKeyNames property with the primary key column i.e. categoryid in our case.

 

<asp:GridView ID="gdview"  runat="server" AutoGenerateColumns="False"  DataKeyNames="CategoryID"  OnRowCancelingEdit="gdview_RowCancelingEdit" OnRowDeleting="gdview_RowDeleting" OnRowEditing="gdview_RowEditing" OnRowUpdating="gdview_RowUpdating" Width="100%">

        <Columns>

            <asp:BoundField HeaderText="Category Name" DataField="CategoryName" SortExpression="CategoryName" >

                <ItemStyle Height="20px" Width="150px" />

            </asp:BoundField>

           

            <asp:CommandField ShowEditButton="True">

                <ItemStyle Width="100px" />

            </asp:CommandField>

            <asp:TemplateField>

            <ItemTemplate>

            <asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete"></asp:LinkButton>

           

            </ItemTemplate>

            <ItemStyle Width="100px" />

       

            </asp:TemplateField>

        </Columns>

 

</asp:GridView>

 



In code behind

 

protected void Page_Load(object sender, EventArgs e)

    {

 

        if (!Page.IsPostBack)

        {

            bindgrid();

            total = 0;

          

        }

 

    }

 

    public void bindgrid()

    {

        SqlConnection conn = new SqlConnection("Data Source='localhost';Initial Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");

        SqlCommand cmd = new SqlCommand("select CategoryName,CategoryID from Categories ", conn);

 

        SqlDataAdapter da = new SqlDataAdapter("", conn);

        da.SelectCommand = new SqlCommand("select CategoryName,CategoryID from Categories", conn);

        DataSet ds = new DataSet();

        da.Fill(ds, "data");

        gdview.DataSource = ds.Tables[0].DefaultView;

        gdview.DataBind();

 

      

    }

    protected void gdview_RowEditing(object sender, GridViewEditEventArgs e)

    {

       

        gdview.EditIndex = e.NewEditIndex;

     

        bindgrid();

    

    }

    protected void gdview_RowUpdating(object sender, GridViewUpdateEventArgs e)

    {

      

        int catid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());

        string strcatname=((TextBox)gdview.Rows[e.RowIndex].Cells[0].Controls[0]).Text;

        SqlConnection conn = new SqlConnection("Data Source='localhost';Initial Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");

        SqlDataAdapter da = new SqlDataAdapter("", conn);

        conn.Open();

        da.UpdateCommand = new SqlCommand("update Categories set CategoryName='" + strcatname + "' where CategoryID=" + catid, conn);

        da.UpdateCommand.ExecuteNonQuery();

        conn.Close();

        gdview.EditIndex = -1;

        bindgrid();

      

 

    }

    protected void gdview_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

    {

        gdview.EditIndex = -1;

        bindgrid();

    }

    protected void gdview_RowDeleting(object sender, GridViewDeleteEventArgs e)

    {

      

        int catid = int.Parse(gdview.DataKeys[0].Value.ToString());

       SqlConnection conn = new SqlConnection("Data Source='localhost';Initial Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");

        SqlDataAdapter da = new SqlDataAdapter("", conn);

        conn.Open();

        da.DeleteCommand = new SqlCommand("delete from Categories where CategoryID="+catid, conn);

        da.DeleteCommand.ExecuteNonQuery();

        conn.Close();

        bindgrid();

    }

 



In the gdview_RowEditing and gdview_RowDeleting event, we have used the below code to retrieve categoryid from datakey of GridView,


int catid = int.Parse(gdview.DataKeys[e.RowIndex].Value.ToString());


Here, e. RowIndex represents the index of the particular row.

 

Similar Articles