.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
abhays
Clintonzz
arronlee
mattyclown
cathyhill345

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

How to Edit,Update,Delete in Gridview

Posted By:Syed Shakeer Hussain       Posted Date: June 16, 2009    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  
 

Update, Delete, Cancel in Gridview

 

In this Article you can learn how to edit, update, delete, and cancel in gridview.

First drag and drop Gridview.In gridview properties set AutoGenarateColumns to False.

Next open Default.aspx source code. To make a columns in Gridview use  <asp:TemplateField>

Here first I created a table name 'emp' in my database.it contains 3 colomns as id,name,marks,I am creating this colomns in gridview as follows:

 





'>

    
 
 <%#Eval("name") %> 


<%#Eval("marks") %>

         


 

In default.asp.cs page fill the gridview using SqlDataAdapter using below code:

      

 SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
        DataSet ds = new DataSet();
        da.Fill(ds, "emp");
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        conn.Close();


Next in Default.asp page select your gridview in Properties set AutoGenarateDeleteButton=True and AutoGenarateEditButton=True.

 

 

 

 

Next we have to write a code for editing,updating,cancel:In Default.aspx source code we have to add

This is used to Edit the Row in Gridview.Here I am going to Edit only two columns name and marks.

 

 

 

 

For Editing a Gridview:

 

 

In Gridview Events:Double Click on RowEditing Event and write below code

 

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

When you click on Edit link it shows Update,Cancel links

 

 

 

 

For Updating a Gridview:

 

Updating link is used to update a Particular row in emp table using Gridview.

 

Double click on RowUpdating Event and write below code

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbl = (Label)row.FindControl("lblid");
        TextBox textname = (TextBox)row.FindControl("textbox1");
        TextBox textmarks = (TextBox)row.FindControl("textbox2");
      
        GridView1.EditIndex = -1;
        conn.Open();
        SqlCommand cmd = new SqlCommand("update  emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
     
        cmd.ExecuteNonQuery();
        conn.Close();
        bind();
      
 
    }

 

 

 For Canceling a gridview row Operation:

 

Cancel Link in used to cancel the particular row operation before upadating.when you click on Gricview it goes in first stage.

 

Double click on RowCancelingEdit Event and wrtie belwo code

 

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

 

For Deleting a Gridview row:

Delete Link is used to delete a Row in a emp table.it permanently deletes a particular Row From GridView

 

Double Click on RowDeleting Event and write below code

 

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbldeleteID = (Label)row.FindControl("lblid");
        conn.Open();
        SqlCommand cmd = new SqlCommand("delete  emp where rowid=" + lbldeleteID.Text + "", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        bind();
    }

 

The Complete code is written as follows:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>





    Untitled Page


    
    
<%#Eval("name") %> <%#Eval("marks") %>
<>

and in your .cs page

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page 
{
    SqlConnection conn;
    protected void Page_Load(object sender, EventArgs e)
    {
        conn = new SqlConnection("Data Source=INTHIYAAZ;Initial Catalog=shakeer;uid=sa;pwd=sa;");
        if(!IsPostBack )
        {
            bind();
       }
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bind();
        
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
    }
   
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbl = (Label)row.FindControl("lblid");
        TextBox textname = (TextBox)row.FindControl("textbox1");
        TextBox textmarks = (TextBox)row.FindControl("textbox2");
       
        GridView1.EditIndex = -1;
        conn.Open();
        SqlCommand cmd = new SqlCommand("update  emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
      
        cmd.ExecuteNonQuery();
        conn.Close();
        bind();
       
    }
    public void bind()
    {
        
        conn.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
        DataSet ds = new DataSet();
        da.Fill(ds, "emp");
        GridView1.DataSource = ds.Tables[0];
        GridView1.DataBind();
        conn.Close();
    }
    protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
       
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
        Label lbldeleteID = (Label)row.FindControl("lblid");
        conn.Open();
        SqlCommand cmd = new SqlCommand("delete  emp where rowid=" + lbldeleteID.Text + "", conn);
        cmd.ExecuteNonQuery();
        conn.Close();
        bind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        bind();
    
    }
}



 Subscribe to Articles

     

Further Readings:

Responses
Author: Mohammad Hussein         Company URL: http://www.dotnetspark.com
Posted Date: August 02, 2009

Thank you Mr. Syed
This article was very useful to me.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: August 03, 2009

welcome Mr Hussein
Author: Mohammad Hussein         Company URL: http://www.dotnetspark.com
Posted Date: August 09, 2009

hi,
I'm having a problem with updating the data source from the GridView
I'm following what you did in the article, but in the GridView1_RowUpdating handler when I execute update statement textname.Text for example gets me the old values not the changed data in the TextBox.

Any idea what the problem is?
Is there an event that fires before the RowUpdating so it binds the old data again with the TextBoxes in the Edit mode?

Thanks in advance.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: August 11, 2009

Hi,
for your porblem use
if(!IsPostBack )
{
bind();
}
you can see in my coding how i had used above code in my article.
and also understand what is the use of 'IsPostBack'
Author: deepa         Company URL:
Posted Date: September 11, 2009

hi,
this was very useful to me..
For me update is not working. i am getting oledbexception was unhandled by user code
No value given for one or more required parameters.

This is my code.
for me GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
it shows null.All values are assigned to null. Can u pls help me?


protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

Label lbl = (Label)row.FindControl("lblid");

//TextBox textID = (TextBox)row.FindControl("textbox1");
TextBox textfirstname = (TextBox)row.FindControl("textbox1");
TextBox textlastname = (TextBox)row.FindControl("textbox2");
TextBox textgender = (TextBox)row.FindControl("textbox3");
TextBox textdateofbirth = (TextBox)row.FindControl("textbox4");
TextBox textaddress= (TextBox)row.FindControl("textbox5");
TextBox textcityname = (TextBox)row.FindControl("textbox6");


GridView1.EditIndex = -1;
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("update EmployeeDetails set firstname=" + textfirstname.Text + " , lastname=" + textlastname.Text + " where ID=" + lbl.Text + "", myConnection);

cmd.ExecuteNonQuery();
myConnection.Close();
Employee_display();
}
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: September 11, 2009

Hi Deepa,
In pageLoad event use !IsPostBack Property.

if(!IsPostBack )
{
bind();
}

you can see in my coding how i had used above code in my article.
and also understand what is the use of 'IsPostBack'
Author: deepa         Company URL:
Posted Date: September 14, 2009

Hi Hussain,

Thanks for your response. I have used IsPostBack Property.
I am new to programming. Can u please help me with this problem because
I am getting the same error?

I am sending the code:

namespace Employee_details
{
public partial class EmpRegDetails : System.Web.UI.Page
{
OleDbConnection myConnection;

protected void Page_Load(object sender, EventArgs e)
{
string conn = Convert.ToString(Application["con"]);
myConnection = new OleDbConnection(conn);
if (!IsPostBack)
{
bind();
}
}
public void bind()
{
myConnection.Open();
OleDbDataAdapter da = new OleDbDataAdapter("select * from EmployeeDetails", myConnection);
Response.Write(da);
DataSet ds = new DataSet();
da.Fill(ds, "EmployeeDetails");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
myConnection.Close();

}

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

protected void GridView1_RowUpdating(object sender, System.Web.UI.WebControls.GridViewUpdateEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

Label lbl = (Label)row.FindControl("lblid");

//TextBox textID = (TextBox)row.FindControl("textbox1");
TextBox textfirstname = (TextBox)row.FindControl("textbox1");
TextBox textlastname = (TextBox)row.FindControl("textbox2");
TextBox textgender = (TextBox)row.FindControl("textbox3");
TextBox textdateofbirth = (TextBox)row.FindControl("textbox4");
TextBox textaddress = (TextBox)row.FindControl("textbox5");
TextBox textcityname = (TextBox)row.FindControl("textbox6");


GridView1.EditIndex = -1;
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();
OleDbCommand cmd = new OleDbCommand("update EmployeeDetails set firstname=" + textfirstname.Text + " , lastname='" + textlastname.Text + "' where RowID=" + lbl.Text + "", myConnection);

// SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);
cmd.ExecuteNonQuery();
myConnection.Close();
bind();
// Response.Redirect("EmpRegform.aspx");
}

protected void GridView1_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
{

GridView1.EditIndex = -1;
bind();
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{

GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

Label lbldeleteID = (Label)row.FindControl("lblid");
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();

OleDbCommand cmd = new OleDbCommand("delete EmployeeDetails where firstname=" + lbldeleteID.Text + "", myConnection);

cmd.ExecuteNonQuery();

myConnection.Close();

bind();

}

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}

}

}

Once again thanks,

Deepa
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: September 15, 2009

Hi Deepa,Your code is correct.
But you had done a little mistake in OledbCommand.You didnot given a single quote for textfirstname bcz it is a varchar datatype.you have to write as

firstname=''" + textfirstname.Text + "''

so use below command and try it in GridView1_RowUpdating:-

OleDbCommand cmd = new OleDbCommand("update EmployeeDetails set firstname=''" + textfirstname.Text + "'' , lastname=''" + textlastname.Text + "'' where RowID=" + lbl.Text + "", myConnection);


Above Rowid is ''numeric'' data type so no nee to give single Quote.

And also in the same way in use belo code Gridview Row updating:-

OleDbCommand cmd = new OleDbCommand("delete EmployeeDetails where Rowid=''" + lbldeleteID.Text + "''", myConnection);



After trying tell me if it helps you or not........


By the way where you from...
Author: deepa         Company URL:
Posted Date: September 15, 2009

Thanks Hussain. Its working now. I have done little mistake.
Thank you for ur time. ur article is very useful 2 me.

I am from Canada. I am working as a web designer. How abt u?
I saw u in dotnetspidr also.

regards,
deepa
Author: deepa         Company URL:
Posted Date: September 15, 2009

Hi Hussain,

One more thing please..
records are not deleting in the grid view. why?

code:
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

Label lbldeleteID = (Label)row.FindControl("lblid");
string conn = Convert.ToString(Application["con"]);
OleDbConnection myConnection = new OleDbConnection(conn);
myConnection.Open();

OleDbCommand cmd = new OleDbCommand("delete from EmployeeDetails where firstname='" + lbldeleteID.Text + "'", myConnection);

cmd.ExecuteNonQuery();

myConnection.Close();

bind();

Could you please help? Thanks
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: September 16, 2009

Hi deepa,
Again you done small mistake in Delete command.Just read the Error or execption carefully.
You wrote

delete from EmployeeDetails where firstname='" + lbldeleteID.Text + "'

above you are deleting a empdetails through id,not with firstname.
Correct code is as follows:-

OleDbCommand cmd = new OleDbCommand("delete from EmployeeDetails where RowID=" + lbldeleteID.Text + "",myConnection);


Author: sbmdude         Company URL:
Posted Date: December 30, 2009

How can I add Delete confirmation pop up message when I want to Delete a record ?...
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: February 09, 2010

Hi SW,
Sorry for giving late response..
for the first error:(Invalid column name 'ST01'.Problem ):-check the Enter Column Name properly of given in a table.

For second Error:write private as Public
eg:public void bind()
{
string connstring = "Data Source=P-PC\\SQLEXPRESS;Initial Catalog=Peers;Integrated Security=True";
cn = new SqlConnection(connstring);
cn.Open();
String str = "Select * from StudentNew";
SqlDataAdapter da = new SqlDataAdapter(str, cn);
DataSet ds = new DataSet();
da.Fill(ds, "StudentNew")
GridView1.DataSource = ds.Tables["StudentNew"];
GridView1.DataBind();

}
Author: Sameer         Company URL: http://www.dotnetspark.com
Posted Date: April 12, 2010

How to delete a row from datagridview in c# windows application using ms-access. I want to delete the data through button event?
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 21, 2010

My delete is not working...It just doesnot fire the Rowdeleting event. I checked my aspx as well but everything seems correct to me there...dont know what could be the reason.

Can you please help me with this?

Thanks in advance.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 21, 2010

hi gdswati,

For Deleting a Gridview row:-

Delete Link is used to delete a Row in a emp table.it permanently deletes a particular Row From GridView

Double Click on RowDeleting Event and write below code.
if also not work,send me the delete code what you had written.

Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

Thanks a lott Syed Sakhir Hussain...I tried what you suggested...but that did not work..the rowdeleting event is not raised...:-(

Here is my code...Please help me here...I tried putting breakpoint on the first line of RowDeleting...but when I click on Delete link...It doesnot stop at the breakpoint in Rowdeleting and the page is loaded as it is..

protected void grdItems_edit_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)grdItems_edit.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("delete bod_items where rowid = '" + lbldeleteID.Text + "'", myConnection);
try
{
myConnection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception err)
{
lblResult.Text = "Error deleting record. ";
lblResult.Text += err.Message;
}
finally
{
myConnection.Close();
}
populateItems();
}
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

Here is my aspx as well..if you want to have a look at it.

<asp:GridView ID="grdItems_edit" runat="server" AllowSorting="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Vertical" width="670px" OnRowCancelingEdit="grdItems_edit_RowCancelingEdit" OnRowEditing="grdItems_edit_RowEditing" OnRowUpdating="grdItems_edit_RowUpdating" OnRowDeleting="grdItems_edit_RowDeleting" DataKeyNames="rowid" OnRowUpdated="grdItems_edit_RowUpdated">
<Columns>
<asp:TemplateField HeaderText = "rowid">
<ItemTemplate>
<asp:Label ID = "lblid" runat = "server"> <%# Eval("rowid") %> </asp:Label>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="invItemQty" HeaderText="QUANTITY" SortExpression="invItemQty" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:BoundField>
<asp:TemplateField SortExpression="invItemDesc" HeaderText="DESCRIPTION">
<ItemTemplate>
<asp:Label id="DESCRIPTION" runat="server"><%# Eval("invItemDesc")%></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Text='<%# Eval("invItemDesc") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:TemplateField>
<asp:BoundField DataField="invItemSerNum" HeaderText="SERIAL NUMBER" SortExpression="invItemSerNum" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:BoundField>
<asp:BoundField DataField="invItemAmt" HeaderText="AMOUNT" SortExpression="invItemAmt" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:BoundField>
<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:CommandField>
</Columns>

<FooterStyle BackColor="Black" ForeColor="Black" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
<EditRowStyle BorderColor="Black" BorderStyle="Solid" />
</asp:GridView>
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

I tried calling other function where I have query to delete row based on id of selected row. But looks like my RowDeleting event is not fired when I click delete.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

Hi gdswati,
I think you did not write !isPostBack Property in PageLoad.
for eg:
protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{
Bind();
}
}

send your page LoadCode.....
waiting for you reply
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

I tried doing that...but then my gridview is populated twice.

Here is my pageload:
protected void Page_Load(object sender, EventArgs e)
{
string InvoiceNumber = "";
if (!this.IsPostBack)
{
if (Request.QueryString["InvoiceNumber"] != null)
{
InvoiceNumber = Request.QueryString["InvoiceNumber"].ToString();
ShowInfo();
}
}
//I tried adding the code you suggested here.
}
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

I tried doing that...but still same problem...my Rowdeleted is not fired

Here is my pageload:
protected void Page_Load(object sender, EventArgs e)
{
string InvoiceNumber = "";
if (!this.IsPostBack)
{
if (Request.QueryString["InvoiceNumber"] != null)
{
InvoiceNumber = Request.QueryString["InvoiceNumber"].ToString();
ShowInfo();
}
}
if (!IsPostBack)
populateItems();
}
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

Hi gdswati,

Put the breakpoint in RowDelete Event.
run it breakpoint.if the breakpoint came in RowDelete Event then the problem is in the ''Row Delete Event''.Or if the break point goes in the PageLoad without going in the RowDelete Event then the problem with PostBak in Pageload.

in Page Load write the code as follows and run it:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ string InvoiceNumber = "";

if (Request.QueryString["InvoiceNumber"] != null)
{
InvoiceNumber = Request.QueryStrin["InvoiceNumber"].ToString();
ShowInfo();
populateItems();
}
}

wating for you reply
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

I did this...but when I click on delete...nothing happens...it doesnot even go to any breakpoint...
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

Hi,
I think the problem occuring due to the below selcetCommand in .aspx source code.

<asp:CommandField ShowEditButton="True" ShowDeleteButton="True" >
<HeaderStyle Font-Size="Small" HorizontalAlign="Center" />
<ItemStyle Font-Names="Arial" Font-Size="Smaller" />
</asp:CommandField>


remove the above <asp:commandFiield....> </asp:CommandField>

and select your Gridveiw.In Gridview Events double click on RowDeleting event..

Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

no change yet...I dont know why this is not working...

I was having same problem with my RowUpdated...even that was not getting triggered after my row was updated...so I wrote different logic..after trying for hours...and now same thing is happening with RowDeleted.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 24, 2010

Hi ,

send code to my emial id
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: May 25, 2010

Thanks a lott Sahkeer...my delete function is working now. Actually, in delete, my id was returning null value and thts the reason it was not deleting any record.
Author: Pradip         Company URL: http://www.pmbodar.somee.com
Posted Date: May 29, 2010

Hello frnds !!
This code use to successfully in edit but my record is not update successfully.
I don't know how it..error is not occur.

pls..somebody help me..Thanx in Advance !!


My Update code is.....


GridViewRow row= (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("no");
TextBox ttitle = (TextBox)row.FindControl("t1");
TextBox thead = (TextBox)row.FindControl("t2");
TextBox tdetail = (TextBox)row.FindControl("t3");
TextBox timage = (TextBox)row.FindControl("t4");


GridView1.EditIndex = -1;
con.ExecuteCommand("update detail set title='" + ttitle.Text + "',head='" + thead.Text + "',detail='" + tdetail.Text + "',image='" + timage.Text + "' where no=" + lbl.Text + "");
filldata();
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: June 01, 2010

Pradip,
Check this code and see if this helps...

// SQL Update CommandSqlCommand
SqlCommand mySqlUpdate = new SqlCommand("Update bod_Items set invItemDesc = @description, invItemQty = @quantity, invItemAmt = @amount, invItemSerNum = @serNum where cInvNum = '" + Request.QueryString["InvoiceNumber"].ToString() + "' and itemNum = @itemNum", myConnection);

//Bound field
TextBox txtQuantity = (TextBox)grdItems_edit.Rows[e.RowIndex].Cells[1].Controls[0];

//template field - Description
grdItems_edit.Rows[e.RowIndex].Cells[0].FindControl("txtDescription");
TextBox txtDescription = (TextBox)grdItems_edit.Rows[e.RowIndex].Cells[2].FindControl("txtDescription");

//bound field
TextBox txtSerNum = (TextBox)grdItems_edit.Rows[e.RowIndex].Cells[3].Controls[0];

//template field
grdItems_edit.Rows[e.RowIndex].Cells[4].FindControl("txtAmt");
TextBox txtAmt = (TextBox)grdItems_edit.Rows[e.RowIndex].Cells[4].FindControl("txtAmt");

// parameters passed to the SQL Update
mySqlUpdate.Parameters.Add("@quantity", SqlDbType.VarChar).Value = txtQuantity.Text;
mySqlUpdate.Parameters.Add("@description", SqlDbType.VarChar).Value = txtDescription.Text;
mySqlUpdate.Parameters.Add("@serNum", SqlDbType.VarChar).Value = txtSerNum.Text;
mySqlUpdate.Parameters.Add("@amount", SqlDbType.VarChar).Value = txtAmt.Text;
mySqlUpdate.Parameters.Add("@itemNum", SqlDbType.Int).Value = Convert.ToInt32(grdItems_edit.DataKeys[e.RowIndex].Values[0].ToString());
mySqlUpdate.ExecuteNonQuery();
Author: Sameer         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

How to add a new empty row in a Datagridview? Using Button event, i am talking about unbound datagrid.
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

Sameer,
you can add textboxes and a Add button next to it. In the event handler for add button, insert the data from the textboxes in your table and then populate the grid again.

let me know if you have any questions.
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

Sameer,
you can add textboxes and a Add button next to it. In the event handler for add button, insert the data from the textboxes in your table and then populate the grid again.

let me know if you have any questions.
Author: Sameer         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

Thanks Swati,

I did it and it works. One more problem is,
Can i insert all the values in datagridview(in DataTable) into the database?
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

Sameer,
How is your gridview setup?
When you say inserting all values in datagridview into database...Do you mean inserting values in all rows and columns from your gridview?
Author: Sameer         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

Not exactly, My datagridview contains some 20 columns, say i am giving values 4 to 5 rows for all the columns, how can i store the values into the database? I am using OLEDB as my back end database.
Author: gdswati         Company URL: http://www.dotnetspark.com
Posted Date: June 03, 2010

Not sure if I am understanding it correctly.

You would change the values for one row at a time right? So cant you use Update?
Author: Sameer         Company URL: http://www.dotnetspark.com
Posted Date: June 04, 2010

I am giving all the values simultaneously into the grid. Well using Update is a good suggestion i will try it, any way thanks a lot for your help swati.
Author: Amala         Company URL: http://www.dotnetspark.com
Posted Date: June 29, 2010

Hello,Ur codings heleps me lot..Thanks for publishing ur code.But i got some problem.when i click update, all data which r present in gridview r duplicated once again
But when the page is loaded the duplicated data was removed , the data was updated ..and i got a proper result.Herewith i send my code
----------------------------------------------------
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

myset = New DataSet
conn = New SqlConnection()
conn.ConnectionString = "initial catalog=home;user id=sa;pwd=''"
conn.Open()
mycomm = New SqlCommand()
mycomm.Connection = conn
conn.Close()

End Sub
Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating


Dim row As GridViewRow
Dim Exp As TextBox
Dim Amount As TextBox
row = GridView1.Rows(e.RowIndex)
Exp = row.FindControl("Textbox1")
Amount = row.FindControl("Textbox2")
GridView1.EditIndex = -1
conn.Open()
mycomm.CommandText = "update get set Amount='" & Amount.Text & "' where Expenses= '" & Exp.Text & "'"
mycomm.ExecuteNonQuery()
bind()
conn.Close()
End Sub


Sub bind()
myadapter = New SqlDataAdapter("select * from get where datename(Month,Currentdate)='" & DropDownList1.SelectedItem.Text & "'", conn)
myadapter.Fill(myset, "get")
GridView1.DataSource = myset.Tables(0)
GridView1.DataBind()
conn.Close()
End Sub
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: June 29, 2010

Hi Amala,
use IsPostBack Property in PageLoad,your problem will solve..I had written the code below,try it.
---------------------------

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
conn = new SqlConnection("your connection string");
If Not Page.IsPostBack then
bind()
End If

End PageLoad

---------------------------------
Below code is same what you had written

Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating


Dim row As GridViewRow
Dim Exp As TextBox
Dim Amount As TextBox
row = GridView1.Rows(e.RowIndex)
Exp = row.FindControl("Textbox1")
Amount = row.FindControl("Textbox2")
GridView1.EditIndex = -1
conn.Open()
mycomm.CommandText = "update get set Amount='" & Amount.Text & "' where Expenses= '" & Exp.Text & "'"
mycomm.ExecuteNonQuery()
bind()
conn.Close()
End Sub

---------------
Sub bind()
conn.Open()
myadapter = New SqlDataAdapter("select * from get where datename(Month,Currentdate)='" & DropDownList1.SelectedItem.Text & "'", conn)
myadapter.Fill(myset, "get")
GridView1.DataSource = myset.Tables(0)
GridView1.DataBind()
conn.Close()
End Sub


Author: Amala         Company URL: http://www.dotnetspark.com
Posted Date: July 01, 2010

Thanks for ur reply sir.....i tried ,but i got the same error
Author: Roji         Company URL: http://www.dotnetspark.com
Posted Date: July 28, 2010

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int taID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
con.Open();
//take properties of data grid view and set data key name.....
SqlCommand cmd = new SqlCommand("delete Table_1 where TabID=" + taID + "", con);
cmd.ExecuteNonQuery();
con.Close();
bind();
}
it works
Author: Prabhu         Company URL: http://www.dotnetspark.com
Posted Date: December 17, 2010

hi..
this s row updating event




protected void EditEmpDetailGrid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row=(GridViewRow)EditEmpDetailGrid.Rows[e.RowIndex];
Label LblEmpUpdateId = (Label)row.FindControl("EmpID");
TextBox EEmpName = (TextBox)row.FindControl("EditTxtEmpName");
TextBox EEmpDesig = (TextBox)row.FindControl("EditTxtEmpDesignation");
TextBox EEmpDOB = (TextBox)row.FindControl("EditTxtEmpDOB");
TextBox EEmpDOJ = (TextBox)row.FindControl("EditTxtEmpDOJ");
TextBox EEmpStatus = (TextBox)row.FindControl("EEmpStatus");
// DropDownList EDDEmpStatus = (DropDownList)row.FindControl("EditDDEmpStatus");
EditEmpDetailGrid.EditIndex = -1;
BalObj.EmployeeID = LblEmpUpdateId.Text.ToString();
BalObj.EmployeeName = EEmpName.Text ;
BalObj.EmployeeDesignation = EEmpDesig.Text;
BalObj.EmployeeDOB =EEmpDOB.Text;
BalObj.EmployeeDOJ =EEmpDOJ.Text ;
BalObj.EmployeeStatus =EEmpStatus.Text;

if (BalObj.EmpDetailUpdate(BalObj) == 1)
{
bind();
LblId.Text = "Updation Finished";
LblId.Visible = true;

}
}
In row updating event no problem.. Here "EmpID" return the RowId value..


This s Row deleting event

protected void EditEmpDetailGrid_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)EditEmpDetailGrid.Rows[e.RowIndex];
Label RowID = (Label)row.FindControl("EmpID");

BalObj.EmployeeID = RowID.Text.ToString();
if (BalObj.EmpDetailDelete(BalObj) == 1)
{
bind();
LblId.Text = "Deletion Finished";
LblId.Visible = true;
}
}
catch (Exception ex)
{
throw;
}
}
BUt here Return ROwID value as NULL. Same "EmpId" used Here.

Please Clear my Doubt. Thanks in Advance
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: December 17, 2010

Hi Prabhu,
Your code is correct.
Have you used ISPostBack propert in PageLoad() Event or not...If you have not used,it may be the problem of ISPostBack.But i am not sure...
Author: Prabhu         Company URL: http://www.dotnetspark.com
Posted Date: December 18, 2010

thank u for ur reply Syed Shakeer Hussain.

I used Ispostback property.. here no problem.. I found my mistake. I used <EditTemplate/> to labelid in source code . So only return null value. there is the problem.

k.. thankyou verymuch..
Author: pankaj         Company URL: http://www.dotnetspark.com
Posted Date: January 04, 2011

there is an problem of editing
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: January 05, 2011

Ho pankaj,
Where is stuck in the code.Can you tell
Author: sridar1         Company URL: http://www.dotnetspark.com
Posted Date: January 31, 2011

Hai ,

I have some doubt on the below code.plz clear my doubt.


Delete Link is used to delete a Row in a emp table.it permanently deletes a particular Row From GridView



Double Click on RowDeleting Event and write below code




protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open()
SqlCommand cmd = new SqlCommand("delete emp where rowid=" + lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();
}



In the above code u will written "double click on row deleting event".If i click the row in gridview the code will appear like this.


protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

}

How to add the above code for row delete and also for insert and update.

Thanks in advance
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: February 01, 2011

Hi,
You have to click on GridViewRow 'RowDeleting' Event.Not a Gridview.You will find Gridview Events on RigthSide.
Author: sridar1         Company URL: http://www.dotnetspark.com
Posted Date: February 01, 2011

will you plz explain the gridview concept in detail.i can't see that gridviewrow "row deleting"event
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: February 01, 2011

Hi,

First select your Gridview.Near Gridview Properties you will find Thunder symbol.Click it.
Author: sridar1         Company URL: http://www.dotnetspark.com
Posted Date: February 01, 2011

Thanks.Will you plz send the coding for inserting values into grid view.I have a doubt below these two lines.

cmd.Parameters.Add("@age", SqlDbType.Int).Value = Convert.ToInt32(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
cmd.Parameters.Add("@companyname", SqlDbType.VarChar).Value = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;


In the above code I had used the datatype "integer" and "varchar".Suppose if we put the other data types like "char or numeric or float or datetime" how to write the code.plz explain.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: February 01, 2011

Hi,
Check this link...
http://msdn.microsoft.com/en-us/library/system.convert(v=vs.95).aspx
Author: sridar1         Company URL: http://www.dotnetspark.com
Posted Date: February 01, 2011

Hai sir,

I Have some other doubt while inserting values into database.plz rectify it.

I has designed the web page with five text boxes and five label boxes with the button.
suppose if i have to add the values form the text boxes into sql database what is the coding
//code
myCommand.CommandText = "Insert into
usr(firstname,lastname,dob,phno,email)
Values('" + firstname.Text + "','" + lastname.Text + "'," +
dob.Text + "," + phno.Text + ",'" + email.Text + "')";

"In the values i put '"+firstname.Text+"' ....like this.My doubt whether i have to give the name of the textbox inside it or we have to declare the firstname in string.
Author: sridar1         Company URL: http://www.dotnetspark.com
Posted Date: February 02, 2011

Hai sir,


I want to convert the tally files into excel format.Hence it is possible by using .net?
Author: sridar1         Company URL: http://www.dotnetspark.com
Posted Date: February 02, 2011

Sorry for inconvinience.i have some other doubt in windows application.

what is the wrong in below code.below code is not updated
cmd.CommandText = "update aircraft set aircraftID='" + textBox1.Text + "',name='" + textBox2.Text + "',type='" + textBox3.Text + "',primaryuser='" + textBox4.Text + "',city='" + textBox5.Text + "' where aircraftID='" + textBox1.Text + "'";
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: February 02, 2011

Hi,
Why you cant post your dought in forums section
Author: shreybyala         Company URL: http://www.dotnetspark.com
Posted Date: February 09, 2011

I copy-pasted the code but I'm getting an error with 'rowid'.
DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'rowID'.
This is the error.
What shall I do?
Author: sib sankar         Company URL: http://www.dotnetspark.com
Posted Date: March 01, 2011

Dear hussain ,
i am sending you a which i written but updating is not working.
Thanks
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
Class1 css = new Class1();
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{ string qq = "select * from sib1";
GridView1.DataSource = css.gridview(qq);
if(!Page.IsPostBack)

GridView1.DataBind();


}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{



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

GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

TextBox textusername = (TextBox)row.FindControl("textbox1");
TextBox textpassword = (TextBox)row.FindControl("textbox2");
Label lbl = (Label)row.FindControl("lbllabel");
GridView1.EditIndex = -1;
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["conn1"].ToString());
con1.Open();

SqlCommand cmd = new SqlCommand("update sib1 set username='"+textusername.Text + " ', password='"+textpassword.Text +"' where slno='"+lbl.Text+"'",con1);


cmd.ExecuteNonQuery();

con1.Close();

GridView1.DataBind();





}

}
}

Author: Santosh         Company URL: http://jainspirit.co.in
Posted Date: March 23, 2011

Dear Sir
I'm having a problem as above code mension in your Article in(Delete ,update in Gridview).
As run the our page not show the GridView in the page .

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="Default5" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
AllowPaging="True" AllowSorting="True" AutoGenerateEditButton="True"
AutoGenerateSelectButton="True" >
<Columns >
<asp:TemplateField HeaderText ="IDNO"><ItemTemplate ><asp:Label ID="lblid" runat ="server" Text ='<%#Eval("rowid") %>' ></asp:Label></ItemTemplate></asp:TemplateField>

<asp:TemplateField HeaderText="Name" ><ItemTemplate > <%#Eval("name") %></ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="textbox1" runat ="server" Text ='<%#Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText ="Marks"><ItemTemplate><%#Eval("marks") %> </ItemTemplate>
<EditItemTemplate >
<asp:TextBox ID="textbox2" runat ="server" Text ='<%#Eval("marks") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>

</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>

</div>
</form>
</body>
</html>



Default.aspx.cs



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
SqlConnection conn;

protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("initial catalog=employees;data source=ICFAI-A7031E0F5\\SQLEXPRESS; integrated security=true");
if(!IsPostBack )
{
bind();
}

}



protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbldeleteID = (Label)row.FindControl("lblid");
conn.Open();
SqlCommand cmd = new SqlCommand("delete student where rowid=" + lbldeleteID.Text + "", conn);
cmd.ExecuteNonQuery();
conn.Close();
bind();

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

public void bind()
{

conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from student", conn);
DataSet ds = new DataSet();
da.Fill(ds, "student");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{

GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");

GridView1.EditIndex = -1;
conn.Open();
SqlCommand cmd = new SqlCommand("update student set marks=" + textmarks.Text + " , name='" + textname.Text + "' where rowid=" + lbl.Text + "", conn);

cmd.ExecuteNonQuery();
conn.Close();
bind();

}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bind();
}
}



Plz.. help me.



Author: mansi         Company URL: http://www.dotnetspark.com
Posted Date: May 03, 2011

Hi..
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label lbl = (Label)row.FindControl("lblid");
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
TextBox txtid = (TextBox)row.FindControl("textbox3");
GridView1.EditIndex = -1;
SqlConnection conn = dummyDbConnection.GetDummyDBConnection();
SqlCommand cmd = new SqlCommand("update emp set marks=" + textmarks.Text + " , name='" + textname.Text + " , rowid='" +txtid .Text + "' where name='" + textname.Text + "'", conn);
cmd.ExecuteNonQuery();
conn.Close();
bindgrid();
}
}
update works fine..but i am getting LBL VALUE ="NULL" IN THIS PARTICULAR LINE Label lbl = (Label)row.FindControl("lblid"); .Please help..
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 04, 2011

Hi mansi,
Your code is correct,
please check once the Label Name correctly or it may have null value in a table.
Author: mansi         Company URL: http://www.dotnetspark.com
Posted Date: May 04, 2011

Hi Syed...

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
OnRowDeleting ="GridView1_RowDeleting" OnRowEditing ="GridView1_RowEditing"
OnRowCancelingEdit ="GridView1_RowCancelingEdit" OnRowUpdating ="GridView1_RowUpdating"
Style="z-index: 100;left: 294px; position: absolute; top: 118px"
AllowPaging="True" AllowSorting="True" BorderColor ="green" ForeColor="#333333" GridLines ="None" BackColor ="#FF8080" >
<Columns>
<asp:CommandField ShowDeleteButton ="true" ShowEditButton="true" />
<asp:TemplateField HeaderText ="ID">
<ItemTemplate><asp:Label LabelID="lblID" runat="server" Text='<%#Eval("rowid")%>'></asp:Label></ItemTemplate>

</asp:TemplateField>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate><asp:Label LabelID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="textbox1" runat ="server" Text ='<%#Eval("name") %>'></asp:TextBox> </EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText ="Marks">
<ItemTemplate><asp:Label LabelID="lblmarks" runat="server" Text='<%#Eval("marks") %>'></asp:Label></ItemTemplate>
<EditItemTemplate><asp:TextBox ID="textbox2" runat ="server" Text ='<%#Eval("marks") %>'></asp:TextBox></EditItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>
<asp:Label ID="lblmessage" runat="server" ></asp:Label>
</div>
</form>
</body>
</html>


Code Behind goes like this

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

}
public void bindgrid()
{
SqlConnection conn = dummyDbConnection.GetDummyDBConnection();
SqlCommand cmd = new SqlCommand("select * from emp",conn );
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
Label id = (Label)row.FindControl("lblID"); //This line gives an Null value for id.
TextBox textname = (TextBox)row.FindControl("textbox1");
TextBox textmarks = (TextBox)row.FindControl("textbox2");
GridView1.EditIndex = -1;
SqlConnection conn = dummyDbConnection.GetDummyDBConnection();
SqlCommand cmd = new SqlCommand("update emp set marks = " + textmarks.Text + " where rowid = " + id.Text , conn);
cmd.ExecuteNonQuery();
conn.Close();
bindgrid();
}
catch (Exception ex)
{
lblmessage.Text = ex.StackTrace.ToString();

}

}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
bindgrid();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SqlConnection conn = dummyDbConnection.GetDummyDBConnection();
string sqlStatment="Delete FROM emp WHERE rowid = @rowid";
try
{
SqlCommand cmd = new SqlCommand(sqlStatment, conn);
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
int idworking = Convert.ToInt32(((Label)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text); //id
cmd.Parameters.AddWithValue("@rowid", idworking);
cmd.ExecuteNonQuery();
bindgrid();

}
catch (Exception ex)
{
string msg = "Deletion Error";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}


Label id = (Label)row.FindControl("lblID"); //This line gives an Null value for id.

TextBox textname = (TextBox)row.FindControl("textbox1"); //This line of code works absolutely fine.

I am very new to gridview.So tryin to learn frm ur code.Ur example v nice to understand.But till now cudnt solve this peace of problem syed.From 2 days i am breaking my head.Pls help.

Author: Adwait         Company URL: http://www.dotnetspark.com
Posted Date: May 08, 2011

Hello i am getting this error-

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Source Error:


Line 118:
Line 119: int index = GridView1.EditIndex;
Line 120: GridViewRow row = GridView1.Rows[index];-- In this line there is showing error.


Line 121: //int SCode = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
Line 122: // int Oid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);


Please can anybody solve this.



protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String connString = ConfigurationManager.ConnectionStrings["MyConnection"].ToString();
SqlConnection conn = new SqlConnection(connString);


//GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
//int SCode = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
// int Oid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
int Oid = Convert.ToInt32(((TextBox)row.Cells[2].Controls[0]).Text.ToString());
string WingNo = ((TextBox)row.Cells[3].Controls[0]).Text.ToString().Trim();
string FlatNo = ((TextBox)row.Cells[4].Controls[0]).Text.ToString().Trim();
string OwnerName = ((TextBox)row.Cells[5].Controls[0]).Text.ToString().Trim();
string CoOwnerName = ((TextBox)row.Cells[6].Controls[0]).Text.ToString().Trim();
string ContAdd = ((TextBox)row.Cells[7].Controls[0]).Text.ToString().Trim();
string City = ((TextBox)row.Cells[8].Controls[0]).Text.ToString().Trim();
string Pincode = ((TextBox)row.Cells[9].Controls[0]).Text.ToString().Trim();
string Phone = ((TextBox)row.Cells[10].Controls[0]).Text.ToString().Trim();
string Mobile = ((TextBox)row.Cells[11].Controls[0]).Text.ToString().Trim();
string Email = ((TextBox)row.Cells[12].Controls[0]).Text.ToString().Trim();
string OwnerVehicleNo = ((TextBox)row.Cells[13].Controls[0]).Text.ToString().Trim();
string OwnerOccupation = ((TextBox)row.Cells[14].Controls[0]).Text.ToString().Trim();
string NOM = ((TextBox)row.Cells[15].Controls[0]).Text.ToString().Trim();

string sql = "DELETE FROM MemberMaster WHERE OwnerName=" + OwnerName + "";



//string sql = "UPDATE MemberMaster SET OwnerMemberID=''" + Oid + "'',WingNo=''" + WingNo + "'',FlatNo=''" + FlatNo + "'',OwnerName=''" + OwnerName + "'',CoOwnerName=''" + CoOwnerName + "'', ContactAddress=''" + ContAdd + "'', City=''" + City + "'', Pincode=''" + Pincode + "'', Phone=''" + Phone + "'', Mobile=''" + Mobile + "'', Email=''" + Email + "'', OwnerVehicleNo=''" + OwnerVehicleNo + "'', OwnerOccupation=''" + OwnerOccupation + "'', NumberofMembers=''" + NOM + "'' WHERE OwnerMemberID=" + Oid + "";


SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
int temp = cmd.ExecuteNonQuery();
conn.Close();
if (temp == 1)
{

lblMessage.Text = "Record delted successfully";
}
GridView1.EditIndex = -1;
FillGrid();

}

Author: minsun         Company URL:
Posted Date: May 27, 2011

I'm having a problem with updating.
Textbox tb_Name = (Textbox)row.FinControl("textbox_Name");

values of textbox_Name not changed.

EX:
Initial : textbox_Name is "member1"
i'm make it changed : "member1111111111"
BUT : when debuging values 0f textbox_Name still "member1"
and result update not changed values it.
Author: minsun         Company URL:
Posted Date: May 27, 2011

I'm having a problem with updating.
Textbox tb_Name = (Textbox)row.FinControl("textbox_Name");

values of textbox_Name not changed.

EX:
Initial : textbox_Name is "member1"
i'm make it changed : "member1111111111"
BUT : when debuging values 0f textbox_Name still "member1"
and result update not changed values it.
Author: Syed Shakeer Hussain         Company URL: http://www.dotnetspark.com
Posted Date: May 28, 2011

Hi minsun,

Have you used IsPostBack in PageLoad event.

eg:-
protected void Page_Load(object sender, EventArgs e)
{
conn = new SqlConnection("conncetion String");
{
if(!IsPostBack )
{
bind();
}
}
}

public void bind()
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from emp", conn);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
conn.Close();
}
Author: eng?         Company URL: http://www.dotnetspark.com
Posted Date: March 05, 2012

hi mr hussain i hope that you are fine and in a good healt
iam new in asp.net and if could u please eplain this code to me the edit and delete links how they appears in the gridview asp:TemplateField HeaderText ="IDNO">

04 <ItemTemplate>

05 <asp:LabelID="lblid"runat="server"Text='<%#Eval("rowid")%>'></asp:Labe>

06 </ItemTemplate>

07 </asp:TemplateField>

08 <asp:TemplateField HeaderText="Name" >

09 <ItemTemplate > <%#Eval("name") %></ItemTemplate>

10 </asp:TemplateField>

11 <asp:TemplateField HeaderText ="Marks">

12 <ItemTemplate><%#Eval("marks") %></ItemTemplate>

13 </asp:TemplateField>

14
thanks in advance
Author: Tanmoy         Company URL: http://www.dotnetspark.com
Posted Date: July 09, 2012

Thanks Mr.Hussain for posting such a helpful article.Its very helpful to me. Thanks again
Author: siva maruthu         Company URL: http://www.dotnetspark.com
Posted Date: July 11, 2012

hai sir..


i tried your code but it show one error...

The call is ambiguous between the following methods or properties: 'food_Non.WebForm4.bind()' and 'food_Non.WebForm4.bind()'.


please help me sir..

Author: ANIL         Company URL: http://www.dotnetspark.com
Posted Date: June 17, 2013

Thank you,
In the same way I want to Edit the images After edit images Save to database using Asp.net gridview.How can i do this please give me the remaining code also

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend