Row Editing in gridview

(ASP.NET)


Hi,
In this article i am updating the gridview row using its row updating event. When the user clicks the row edit button in the gridview row, the gridview row will go to the edit mode. In the edit mode user can change the data for the current record and click the update button. In the row updating event of the gridview i get the updated record and update in the database.

.aspx page

 <div>
     
        <asp:GridView ID="grdvw_products" OnRowDataBound="grdvw_products_RowDataBound" DataKeyNames="ProductName,ProductID" OnPageIndexChanging="grdvw_products_PageIndexChanging" OnRowUpdating="grdvw_products_RowUpdating" OnRowCancelingEdit="grdvw_products_RowCancelingEdit" OnRowEditing="grdvw_products_RowEditing" AllowPaging="True" AutoGenerateColumns="False" runat="server">
             <Columns>
             <asp:CommandField CausesValidation="false" ShowEditButton="true" HeaderText="Edit" />

             <asp:TemplateField HeaderText="Product ID">
                 <ItemTemplate>
                     <asp:Label ID="lbl_productid" runat="server" Text='<%#Eval("ProductID") %>' />
                 </ItemTemplate>
             </asp:TemplateField>
         
                   <asp:TemplateField  HeaderText="Product Name">
            <ItemTemplate>
            <%# Eval("ProductName")%>
            </ItemTemplate>
            <EditItemTemplate>
              
               <asp:TextBox style="background:orange; width:100px;" ID="txt_updtprod" runat="server" Text='<%#Eval("ProductName")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
                 </Columns>

        </asp:GridView>
       
    </div>


Codebehind file:-

 protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    bindgridView();
                }
            }
            catch (Exception)
            { }
        }

        private void bindgridView()
        {
            try
            {
                SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwindconstring"].ToString());
                string query = "select * from Products";
                DataSet ds = new DataSet();
              

                SqlDataAdapter sqldt = new SqlDataAdapter(query, sqlcon);
                sqldt.Fill(ds);

                grdvw_products.DataSource = ds;
                grdvw_products.DataBind();

              
               
            }
            catch (Exception)
            { }
        }

        protected void grdvw_products_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
               
                grdvw_products.EditIndex = e.NewEditIndex;
                bindgridView();
               
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }

        protected void grdvw_products_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                //for update operation
                GridViewRow row = (GridViewRow)grdvw_products.Rows[e.RowIndex];
             
                string productid = grdvw_products.DataKeys[row.RowIndex][1].ToString();
                SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwindconstring"].ToString());

                TextBox txt_productName = (TextBox)row.FindControl("txt_updtprod");
                SqlCommand cmd = new SqlCommand("Update Products Set ProductName=@prodName Where ProductID=@prodID", sqlcon);
                cmd.Parameters.Add("@prodID", SqlDbType.Int).Value = productid;
                cmd.Parameters.Add("@prodName", SqlDbType.NVarChar).Value = txt_productName.Text;


                sqlcon.Open();
                cmd.ExecuteNonQuery();
                sqlcon.Close();

                //if you want, give update successful message
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + txt_productName.Text + " details updated successfully')", true);
                //end of update operation
                grdvw_products.EditIndex = -1;
            
                bindgridView();
               
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }

        protected void grdvw_products_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                grdvw_products.EditIndex = -1;
                bindgridView();
               
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }

        protected void grdvw_products_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grdvw_products.PageIndex = e.NewPageIndex;
                //while moving to the next page, clear the viewstate
                ViewState["delRows"] = null;

                bindgridView();
            }
            catch (Exception)
            { }
        }

Image

Ratings


Average Rating: 0.00 by 0 users
Giri Prasad
6/20/2013
6/20/2013
Download PDF

Comments