ASP.NET - how to edit gridview control - Asked By aman on 09-Jul-11 02:49 AM

hi all,

i want to know how exactly i can edit gridview control........


thanks and regards
Aman Khan
Radhika roy replied to aman on 09-Jul-11 02:53 AM
For editing in GridView you have to use GridViewRowEditing() Event.

In this event you have to write code.

Use this code-=

In the RowEditing event of the GridView, add the following lines of code. This will switch a specific row of the GridView to Edit Mode.

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

After the GridView swithes to Edit Mode, you can view the TextBoxes and DropDownlList controls along with Update and Cancel linkbuttons in the Edit mode. To cancel this action, add the following two lines of code in the GridView’s RowCancelingEdit event.

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
  GridView1.EditIndex = -1;
   FillCustomerInGrid();
}
You can update the data to the customer table, by adding the following lines of code in the GridView’s RowUpdating event.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
  TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtName");
  DropDownList cmbGender = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbGender");
  TextBox txtCity = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCity");
  DropDownList cmbType = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("cmbType");

 customer.Update(GridView1.DataKeys[e.RowIndex].Values[0].ToString(),txtName.Text, cmbGender.SelectedValue,txtCity.Text, cmbType.SelectedValue);
  GridView1.EditIndex = -1;
  FillCustomerInGrid();
}

The above block of codes in RowUpdating event, finds the control in the GridView, takes those values in pass it to the CustomersCls class Update method. The first parameter GridView1.DataKeys[e.RowIndex].Values[0].ToString() will return the Code of the Customer. That is the unique code for each customer to perform update function.

Follow this link also-

http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx

Hope this will help you.
Web Star replied to aman on 09-Jul-11 03:11 AM
There are complete example with code how can you make editable gridviewhttp://www.codeproject.com/KB/webforms/Editable_GridView.aspx
SRE replied to aman on 09-Jul-11 03:35 AM
Hi Below are the best articles to know how to work with GridView in asp.net.

http://www.dotnetfunda.com/articles/article29.aspx

http://www.codeproject.com/KB/ajax/GridViewKeyboardExtender.aspx

Hope This Will Help You
Reena Jain replied to aman on 09-Jul-11 03:44 AM
Hi,

I would like to give this example to edit gridview

On .aspx page

<Columns>
  <asp:TemplateField>
  <ItemTemplate>
  <asp:ImageButton ID="check" runat="server" ImageUrl='<%# GetImageUrl(Eval("Check")) %>' />
  </ItemTemplate>
  </asp:TemplateField>
</Columns>

on .aspx.cs page

public string GetImageUrl(object checkObject)
{
   if (checkObject!= null)
   {
  bool check;
  bool parsable = bool.Parse(checkObject.ToString(), out check);
  check= parsable ? check : false;
 
  return check ? "~/Media/Images/tick.png" : "~/Media/Images/untick.png";
   }
 
   return "~/Media/Images/none.png";
}

hope this will help you
dipa ahuja replied to aman on 09-Jul-11 04:02 AM
Untitled document
1. Take Gridview on your webpage.
2. Right Click on it , and choose "Add new Column" from that dialogBox select commandField from the combobox, which will allow you to add "select, edit/update and delete" buttons on your GridView.


 
3.Now implement following events of Gridview
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
 
.CS Code
 
static string ConnString ="ConnectionString";
protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
   //Code to bind gridview
   }
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
   GridView1.EditIndex = e.NewEditIndex;
   //Code to bind gridview
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
   int id = int.Parse(((Label)GridView1.Rows[e.RowIndex].FindControl("lblid")).Text);//ID
   string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname")).Text;
  SqlConnection connect = new SqlConnection(ConnString);
   connect.Open();
  string q = "Update people set name=@name where id=@id";
  SqlCommand comm = new SqlCommand(q, connect);
   comm.Parameters.AddWithValue("name", name);
   comm.Parameters.AddWithValue("id", id);
   comm.ExecuteNonQuery();
   connect.Close();
  GridView1.EditIndex = -1;
    //Code to bind gridview
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
   GridView1.EditIndex = -1;
   BindGrid();
}

Jitendra Faye replied to aman on 09-Jul-11 06:20 AM

For Edit ,Update and Delete in GridView You have to Implement following Events of GridView-

1. RowEditing
2. RowCancelingEdit
3. RowUpdating

Try this code sample

.aspx code-

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false"
DataKeyNames ="empid" onrowcancelingedit="GridView2_RowCancelingEdit"
onrowediting="GridView2_RowEditing"
onrowupdating="GridView2_RowUpdating"
onrowcommand="GridView2_RowCommand"
>
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField ="empid" HeaderText ="empid"/>
<asp:BoundField DataField ="empname" HeaderText ="empname"/>

<asp:TemplateField HeaderText ="dept">
<ItemTemplate>
<%# Eval("dep") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server" DataSourceID="SqlDataSource1" ID="DropDeptId" DataTextField="Deptid"
DataValueField="DeptId" />
</EditItemTemplate>

</asp:TemplateField>
<asp:CommandField ShowEditButton ="true" ShowDeleteButton ="true" />
</Columns>
</asp:GridView>

.cs code-

//nction to bind Grid

private void getdata()
{
SqlConnection con = new SqlConnection("CONNECTION STRING");
SqlDataAdapter da;
string mySQL = "SELECT empid,empname,dept FROM emp ";
da = new SqlDataAdapter(mySQL, con);
con.Open();
DataSet ds = new DataSet();
da.Fill(ds);
GridView2.DataSource = ds;
GridView2.DataBind();
}

Code to delete

protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; //FOR GETTING ENPID

string deleteQuery = "delete from emp where empid= ' " + strEmpId + " ' ";
SqlConnection cn = new SqlConnection("CONNECTION STRING");
cn.Open();
SqlCommand cmd = new SqlCommand(deleteQuery, cn);
cmd.ExecuteNonQuery();
cn.Close();
GridView1.EditIndex = -1;
Response.Write("<script>alert('Record Deleted')</script>");
getdata();

}


Code to edit

protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView2.EditIndex = e.NewEditIndex;
getdata();
}
protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView2.EditIndex = -1;
getdata();
}

Code to Update

protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; //FOR GETTING ENPID
string strEmpName= GridView1.Rows[e.RowIndex].Cells[2].Text; //FOR GETTING ENPNAME

string strDeptId = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DropDeptId")).SelectedValue.ToString();
string UpdateQuery = "update emp set empname= '" + strEmpName + "' ,dep='" + strDeptId + "' where empid= ' " + strEmpId + " ' ";
SqlConnection cn = new SqlConnection("CONNECTION STRING");
cn.Open();
SqlCommand cmd = new SqlCommand(UpdateQuery, cn);
cmd.ExecuteNonQuery();
cn.Close();
GridView1.EditIndex = -1;
getdata();
Response.Write("<script>alert('Record Updated')</script>");
}

Try this code and let me know.

Ravi S replied to aman on 09-Jul-11 06:57 AM
HI

try this

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

    public void bindGridView()
    {
      // string variable to store the connection string
      // defined in ConnectionStrings section of web.config file.
      string connStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

      // object created for SqlConnection Class.
      SqlConnection mySQLconnection = new SqlConnection(connStr);

      // if condition that can be used to check the sql connection
      // whether it is already open or not.
      if (mySQLconnection.State == ConnectionState.Closed)
      {
        mySQLconnection.Open();
      }

        SqlCommand mySqlCommand = new SqlCommand("SELECT CategoryID, CategoryName, Description FROM categories", mySQLconnection);
        SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
        DataSet myDataSet = new DataSet();
        mySqlAdapter.Fill(myDataSet);

      GridView1.DataSource = myDataSet;
      GridView1.DataBind();


      // if condition that can be used to check the sql connection
      // if it is open then close it.
      if (mySQLconnection.State == ConnectionState.Open)
      {
        mySQLconnection.Close();
      }
    }

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

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
      GridView1.EditIndex = -1;
      bindGridView();
    }

associated with GridView.

refer

http://programming.top54u.com/post/ASP-Net-Gridview-Edit-Update-Cancel-Commands.aspx