Geeks With Blogs

News

Microsoft MVP


Moderator at CodeASP.NET


Quiz Master




free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

This demo is a continuation of my previous example “Binding GridView with Data”. If you are not familiar of binding the GridView the ado.net way then I would suggest looking at my previous example first before you proceed to this example.

Basically, this demo describes the basic way to do INSERT, EDIT, UPDATE  and DELETE data in ASPNET GridView Control using the ADO.NET way. 

STEP  1: Creating  a DataBase Table

In this demo, I presumed that you already have a basic background on how to create a simple database table. In this example, this time I used my own database called SampleDB which has Customers Table and basically contains the following field columns:

CustomerID – PK

CompanyName

ContactName

ContactTitle

Address

Country

 

STEP 2: Setting Up the Connection String

      <connectionStrings>

            <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SampleDB.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>

      </connectionStrings>

 

STEP 3: Setting up the GUI

Just for the simplicity of this demo, I set up the GUI like this:

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>GridView Data Manipulation</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <table cellpadding="0" cellspacing="0">

            <tr>

                <td style="width: 100px; height: 19px;">

                    Company ID</td>

                <td style="width: 100px; height: 19px;">

                    Company</td>

                <td style="width: 100px; height: 19px;">

                    Name</td>

                <td style="width: 100px; height: 19px;">

                    Title</td>

                <td style="width: 100px; height: 19px;">

                    Address</td>

                <td style="width: 100px; height: 19px;">

                    Country</td>

            </tr>

            <tr>

                <td style="width: 100px">

                    <asp:TextBox ID="TextBox1" runat="server"/></td>

                <td style="width: 100px">

                    <asp:TextBox ID="TextBox2" runat="server"/></td>

                <td style="width: 100px">

                    <asp:TextBox ID="TextBox3" runat="server"/></td>

                <td style="width: 100px">

                    <asp:TextBox ID="TextBox4" runat="server"/></td>

                <td style="width: 100px">

                    <asp:TextBox ID="TextBox5" runat="server"/></td>

                <td style="width: 100px">

                    <asp:TextBox ID="TextBox6" runat="server"/></td>

                <td style="width: 100px">

                    <asp:Button ID="Button1" runat="server"

                                Text="Add New"

                                OnClick="Button1_Click" />

                </td>

            </tr>

        </table>

       

        <asp:GridView ID="GridView1" runat="server"

                      AutoGenerateColumns="false"

                      ShowFooter="true">

        <Columns>

            <asp:BoundField DataField="CustomerID"

                            HeaderText="ID" ReadOnly="true"/>

            <asp:BoundField DataField="CompanyName"

                            HeaderText="Company"/>

            <asp:BoundField DataField="ContactName" HeaderText="Name"/>

            <asp:BoundField DataField="ContactTitle"

                            HeaderText="Title" />

            <asp:BoundField DataField="Address" HeaderText="Address"/>

            <asp:BoundField DataField="Country" HeaderText="Country"/>

        </Columns>

        </asp:GridView>

    </div>

    </form>

</body>

</html>

 

Note:  I have set the CustomerID field to ReadOnly so that the field cannot be edited.

STEP 4: Binding GridView with Data

I will not elaborate on this step because I already describe the details in my previous example about “Binding GridView with Data”. Here are the code blocks for binding the GridView.

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            BindGridView();

        }

    }

 

    private string GetConnectionString()

    {

        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

    }

 

    #region Bind GridView

    private void BindGridView()

    {

        DataTable dt = new DataTable();

        SqlConnection connection = new SqlConnection(GetConnectionString());

        try

        {

            connection.Open();

            string sqlStatement = "SELECT Top(10)* FROM Customers";

            SqlCommand cmd = new SqlCommand(sqlStatement, connection);

            SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);

 

              sqlDa.Fill(dt);

              if (dt.Rows.Count > 0)

              {

                GridView1.DataSource = dt;

                GridView1.DataBind();

              }

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

                string msg = "Fetch Error:";

                msg += ex.Message;

                throw new Exception(msg);

        }

        finally

        {

            connection.Close();

        }

    }

    #endregion

}

 

Now, we already know how to bind our GridView with data from database. So let’s proceed on adding a new data in GridView.

STEP 5: Adding New Data in GridView

As you have noticed in STEP 2, we have added six TextBox and a Button in the web form in order for us to type the information there and Insert them to the database. Now let’s create a method for executing the Update or Insert.

Here are the code blocks for our Insert and Update method in the code behind:

#region Insert New or Update Record

    private void UpdateOrAddNewRecord(string ID, string Company, string Name, string Title, string Address, string Country, bool isUpdate)

    {

        SqlConnection connection = new SqlConnection(GetConnectionString());

        string sqlStatement = string.Empty;

 

        if (!isUpdate)

        {

            sqlStatement = "INSERT INTO Customers"+

"(CustomerID,CompanyName,ContactName,ContactTitle,Address,Country)" +

"VALUES (@CustomerID,@CompanyName,@ContactName,@ContactTitle,@Address,@Country)";

        }

        else

        {

            sqlStatement = "UPDATE Customers" +

                           "SET CompanyName = @CompanyName,

                           ContactName = @ContactName," +

                           "ContactTitle = @ContactTitle,Address = 

                           @Address,Country = @Country" +

                           "WHERE CustomerID = @CustomerID,";

        }

        try

        {

            connection.Open();

            SqlCommand cmd = new SqlCommand(sqlStatement, connection);

            cmd.Parameters.AddWithValue("@CustomerID", ID);

            cmd.Parameters.AddWithValue("@CompanyName", Company);

            cmd.Parameters.AddWithValue("@ContactName", Name);

            cmd.Parameters.AddWithValue("@ContactTitle", Title);

            cmd.Parameters.AddWithValue("@Address", Address);

            cmd.Parameters.AddWithValue("@Country", Country);

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Insert/Update Error:";

            msg += ex.Message;

            throw new Exception(msg);

 

        }

        finally

        {

            connection.Close();

        }

    }

    #endregion

 

The UpdateOrAddNewRecord is a method that takes seven parameters.  Six of those paramaters basically comes from the TextBox values that were entered in the page. The last parameter is a boolean value which tells the method whether to execute an Insert (false) or Update (true). Default is true.

Here’s the code block for calling the method UpdateOrAddNewRecord on Button_Click event and pass the corresponding parameters needed:

    protected void Button1_Click(object sender, EventArgs e)

    {

        UpdateOrAddNewRecord(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text, TextBox6.Text, false);

        //Re Bind GridView to reflect changes made

        BindGridView();

    }

 

As you can see from above, We have called the BindGridView() method again in order to reflect the changes made and display the new added data in the GridView. See output below with red mark.

 

STEP 6: Edit and Update Records In GridView

One of the good things about GridView is that it provides a built-in CommandField Buttons which allows us to perform certain actions like editing, updating,deleting and selecting of GridView data.

To add those command fields mentioned in the GridView you can follow these few steps below:

1.       Switch to Design View

2.       Right Click on the GridView and Select  --> Show Smart Tag --> Add New Columns

3.       On the List Select CommandField

4.       Check Delete and Edit/Update options then OK

 

As you can see the Edit and Delete CommandField are automatically added in the last column of GridView.  Now we can start to write our codes for editing and updating the information in the GridView.

 

In-order to perform Edit and Update in GridView we need to use three events ( GridView_RowEditing, GridView_RowCancelingEdit , GridView_RowUpdating). For those who do not know on how to generate Events in GridView you can follow these steps below:

 

1.       Switch to Design View in Visual Studio Designer

2.       Click on the GridView

3.       Navigate to the GridView Property Pane and then SWITCH to Event Properties

4.       From there you would be able to find the list of events including those three  events mentioned above

5.       Double Click on that to generate the Event handler for you

6.       Then write the codes there

 

Here’s the code for each events:

 

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

        GridView1.EditIndex = e.NewEditIndex; // turn to edit mode

        BindGridView(); // Rebind GridView to show the data in edit mode

}

 

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

        GridView1.EditIndex = -1; //swicth back to default mode

        BindGridView(); // Rebind GridView to show the data in default mode

}

 

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

        //Accessing Edited values from the GridView

        string id = GridView1.Rows[e.RowIndex].Cells[0].Text; //ID

        string company = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; //Company

        string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; //Name

        string title = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text; //Title

        string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text; //Address

        string country = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text; //Country

 

        UpdateOrAddNewRecord(id,company,name,title,address,country,true); // call update method

        GridView1.EditIndex = -1;

        BindGridView(); // Rebind GridView to reflect changes made

}

 

STEP 7: Perform Delete in GridView

 

Since we are using the Built-in Delete CommandField Button in GridView, we can use the GridView_RowDeleting event to delete specific row in GridView.

 

Here’s the code block for the Delete method:

#region Delete Record

    private void DeleteRecord(string ID)

    {

        SqlConnection connection = new SqlConnection(GetConnectionString());

        string sqlStatement = "DELETE FROM Customers WHERE CustomerID = @CustomerID";

        try

        {

            connection.Open();

            SqlCommand cmd = new SqlCommand(sqlStatement, connection);

            cmd.Parameters.AddWithValue("@CustomerID", ID);

            cmd.CommandType = CommandType.Text;

            cmd.ExecuteNonQuery();

        }

        catch (System.Data.SqlClient.SqlException ex)

        {

            string msg = "Deletion Error:";

            msg += ex.Message;

            throw new Exception(msg);

 

        }

        finally

        {

            connection.Close();

        }

    }

#endregion

 

Here’s the code block for calling the delete method at RowDeleting event

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

   string id = GridView1.Rows[e.RowIndex].Cells[0].Text; get the id of the selected row

   DeleteRecord(id);//call delete method

   BindGridView();//rebind grid to reflect changes made

}

 

That’s it!

Note: If you wan’t to display a confirmation when deleting a row in GridView then you can refer to my next example about “Display Confirmation Message on GridView Deleting

Technorati Tags: ,,,
Posted on Sunday, February 22, 2009 1:34 AM ADO.NET , ASP.NET , C# , GridView | Back to top


Comments on this post: GridView Insert, Edit, Update and Delete – The Ado.Net way

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Thank you. I am using "GridView1.Rows[e.RowIndex].Cells[0].Text " for getting delete id. It's taking "" value. But it must take "3" .why :( ?
Left by deep&blue on Feb 23, 2009 1:33 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I've solved my problem, thank you..
Left by deep&blue on Feb 23, 2009 1:53 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
good description with example.
Left by aalap on Mar 19, 2009 10:06 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
hi deep&blue,
can u suggest me how u got that id=3
Left by suresh on Mar 25, 2009 8:05 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I have a project that I coppied the above code into. When I do an update, and get to the GridView1_RowUpdating, there is no value passed to "ID", and then when I go to the next row for "Company" I get the following error:

Specified argument was out of the range of valid values.
Parameter name: index

Any idea what I need to do to fix this issue?

Thanks
Left by Scott Brown on Apr 02, 2009 7:19 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi

This is a very helpful site for people like me to understand the coding concepts in a simple manner.

Really GoodOne....ThankYou
Left by Rajesh U on May 07, 2009 8:01 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
hai ,
U have done rellay superb job..., with basic you have explained everything clearly.
Left by Sarvesh on Jun 11, 2009 1:55 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
In your demo, do you have EDIT/UPDATE/CANCEL button links? Would you please send me a complete source codes?

Thanks,
Sharon
Left by Sharon on Jul 01, 2009 10:28 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi

Yes, Vinz I see your http://aspsnippets.com/post/2009/06/25/ASPNet-GridView-Insert-Edit-Update-and-Delete-the-ADONET-way.aspx. It is very useful to us in practical in our collage project. And thankful of this link.

thanks,

Ritesh vyas
Left by Ritesh Vyas on Aug 22, 2009 9:26 PM

# Re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi Ritesh Vyas

It is very help to us and I thanks for your advise for reference of this blog.

thanks,

Ravi Khoda
Left by Ravi Khoda on Aug 26, 2009 2:28 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
You made it look simple

hats off to you
Left by Leather on Sep 03, 2009 12:57 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
great job and understanding
Left by yahya on Oct 08, 2009 5:04 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
How to update a dropdownlist in the gridview?
I tried to use this: DropDownList ddl = (DropDownList)GridView5.Rows[e.RowIndex].Cells[7].FindControl("DDL");
project = Server.HtmlEncode(ddl.SelectedItem.Text);
But got this error: System.InvalidCastException: Unable to cast object of type 'System.Web.UI.LiteralControl' to type 'System.Web.UI.WebControls.TextBox'.
Left by tao on Oct 26, 2009 5:21 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
this is awesome. Thanks for sharing the information
Left by Thao on Dec 01, 2009 5:21 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I have a project that I coppied the above code into. When I do an update, and get to the GridView1_RowUpdating, there is no value passed to "ID", and then when I go to the next row for "Company" I get the following error:

Specified argument was out of the range of valid values.
Parameter name: index

Any idea what I need to do to fix this issue?

Thanks
Left by Prashant on Dec 18, 2009 8:59 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
it is not work it never update the value it get old from the database and update to with existing values i want to update with latest value through the grid view
Left by yasir on Jan 22, 2010 1:33 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Sir,

I am using one field in date format of dd/mm/yyyy.It is showing the error as string is not recognised as valid date format. How to insert/update that field? Please help me
Left by SHANTHI on Jan 27, 2010 2:18 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Its wonderful exapmle..
Left by Divakar on Feb 05, 2010 3:09 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Thanx buddy......

Its really gr8.........

Left by Ankit on Mar 17, 2010 8:51 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
can we display blank gridview if no records are there in the database tables
Left by reet on Mar 18, 2010 4:02 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
ewferhtrjyu
erght
rethyhj
tynhjy
Left by 4y45 on Apr 29, 2010 1:49 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
that cmd do not work fine string id = GridView1.Rows[e.RowIndex].Cells[0].Text;
bit when ichange it to string id =((TextBox) GridView1.Rows[e.RowIndex].Cells[0].Contol[0])Text; it werk just Fine any comment
and thx for the code
Left by Tarek on May 08, 2010 2:43 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Instead of adding a CustomerID to your table and later pulling the text to get the ID number, a more reliable way to do it is to add a DataKeyNames field to the grid view.

for example in the .aspx page:
<asp:GridView ID="GridView1" runat="server"
DataKeyNames="CustomerID">
</asp:GridView>

You can then access this information at any time with the following in code:
GridView1.DataKeys[RowIndex]["CustomerID"]

in the Update event it would be something like:
int CustomerID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex]["id"]);

You can do this with any field, but I've found customers get confused when they see the ID field and kept asking me why it was there, this also eliminates any issues if you change the display order of your table later (maybe add an edit/update/cancel control)
Left by John Ryan on May 15, 2010 6:09 AM

# heeelp
Requesting Gravatar...
Hey...great article ;)
But I got a problem... some of my DB fields are float or int... I've tried to convert them. It just keeps getting me errors about the conversion when i'm trying to update the fields. So here I go with my example:

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Accessing Edited values from the GridView
string Cod = GridView1.Rows[e.RowIndex].Cells[0].Text;
string Den = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string Marca= ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string Descr= ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
string Categ = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
string Um = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;

float PA = float.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text);
float PL = float.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text);
int CodF = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[8].Controls[0]).Text);
int Stoc = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[9].Controls[0]).Text);


UpdateOrAddNewRecord(Cod, Den, Marca, Descr, Categ, Um, PA,PL,CodF,Stoc, true); // call update method
GridView1.EditIndex = -1;
BindGridView(); // Rebind GridView to reflect changes made
}

and the debugger says:
Exception Details: System.FormatException: Input string was not in a correct format. Line 136:

Source Error:


Line 134: string Um = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
Line 135:
Line 136: float PA = float.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text);
Line 137: float PL = float.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text);
Line 138: int CodF = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[8].Controls[0]).Text);


Is there another way to convert them?
P.S: I will appreciate your help - I'm trying to do this for my diploma and I'm kinda depressed :)) please help :D
Left by skillz on May 25, 2010 7:02 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hey... it still won't work :(
can I contact you somehow? :D any yahoo or msn adress? thanks.
Left by skillz on May 25, 2010 2:34 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hey lovely article, I was getting lost in msdn but your article helped me out!
Left by Prasenjit on Jul 16, 2010 12:59 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
cool example I will have to try it out
Left by Digital Doomsday on Aug 23, 2010 12:56 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
hey thanx dude ...except for few changes evrythng wokred fine for me ..\

thanx a lot !!!

gr8 work
:)
Left by AruN on Aug 31, 2010 1:58 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi,
Thank you for the great article! You really know how to present the complex matter in a clear and simple way.
Thank to John Ryan for the appropriate contribution, too.
Left by Mira on Sep 14, 2010 6:30 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi
This is great but i have problem when updating the data
after i cant edit the value
Left by Mohanraj on Dec 10, 2010 8:47 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
textbox not accepted in gridview ,please help
Left by santhana on Dec 14, 2010 2:33 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@Mohanraj,

What exactly do you mean by "not able to edit the value?".
Left by Vinz on Dec 14, 2010 4:53 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@santhana,
can you please elaborate more?
Left by Vinz on Dec 14, 2010 4:53 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
i understand this codes. i ll try

thanks.
Left by @Mohankumar.S on Jan 25, 2011 1:15 PM

# insert,update and delete in GridView Control without writing a single piece of code in C# or VB
Requesting Gravatar...
try this link
for insert,update and delete in GridView Control without writing a single piece of code in C# or VB

http://vijayvigneshonflex.blogspot.com/p/how-to-do-insertupdatedelete-and-select.html
Left by Vijay on Jan 26, 2011 8:36 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@Vijay,

Well that's because you are using SqlDataSource control. This article demonstrate how to do CRUD operations in GridView without using DataSource control such as SDC.
Left by Vinz on Jan 26, 2011 11:58 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I am trying this above method but it returns me the old value. I am trying to change the value in textbox but after submitting the changed value is not coming. It gives me the old textbox value. Can anybody tell what my problem may be?
Left by Shuvankar on Feb 16, 2011 10:24 PM

# please give solution.
Requesting Gravatar...
my gridview updating code like this........
----------------------------------------------------------------------------------------
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string st2, st3, st4, st5, st6,st1;
st1 =GridView1.Rows[e.RowIndex].Cells[2].Text .ToString ();
st2 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString();
st3 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString();
st4 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString();
st5 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text.ToString();
st6 = ((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text.ToString();
SqlCommand cmd = new SqlCommand("update districtinfo set district ='" + st2 + "' where id =" + st1 + "", cn);
//SqlCommand cmd = new SqlCommand("update districtinfo set district ='" + st2 + "' , taluka ='" + st3 + "' , crope ='" + st4 + "' , piyat ='" + st5 + "' , area ='" + st6 + "' where id =" + st1 + "", cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();

GridView1.EditIndex = -1;
filldata();
}
------------------------------------------------------------------------------------
and i got error like this..
----------------------------------------------------
Incorrect syntax near '='.
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.Data.SqlClient.SqlException: Incorrect syntax near '='.

Source Error:

Line 62: SqlCommand cmd = new SqlCommand("update districtinfo set district ='" + st2 + "' , taluka ='" + st3 + "' , crope ='" + st4 + "' , piyat ='" + st5 + "' , area ='" + st6 + "' where id =" + st1 + "", cn);
Line 63: cn.Open();
Line 64: cmd.ExecuteNonQuery();
Line 65: cn.Close();
Line 66:
-----------------------------------------------------------------------
please give me help...thanks..
Left by Umesh on Mar 24, 2011 4:43 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@Umesh,

Put space after each equal operator. But I discourage this kind of approach. I would not recommend you to append the values directly into your SQL statements , use Parameterized Query instead for security and readabily of codes..
Left by Vinz on Mar 24, 2011 2:02 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
really an excellent tutorial!!!

thanks .. really it helped me a lot...

excellent coding.....
Left by MANOJ on Apr 09, 2011 3:25 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
really an excellent tutorial!!!

thanks .. really it helped me a lot...

excellent coding .....
i really learnt abt gridview from this tutorial!!!
Left by MANOJ on Apr 09, 2011 3:25 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
thank uoy for solw my problem

???????????BY BYB YB????????????

nice to mit you

ok
Left by PRAVIN SATVANI on Apr 19, 2011 7:29 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
nice description of gridview functions.but i wanna ask that-"I have an aspx page.on that there is a dropdownbox.there are multiple table names in the dropdownbox.and when we select any of them the table would be shown in the gridview.so how to use insert,update,delete,edit in this gridview control.
please reply
Left by ferhat syed on Apr 20, 2011 2:06 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@ferhat syed,

I'd suggest you to post your query at the forums (forums.asp.net or codeasp.net) to get more help from the members there.
Left by Vinz on Apr 20, 2011 4:28 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi,

i have to read data from excel which is uploaded to server and delete first 12 rows and save the remaining data into a table(which is already created).
Can any one help me in urgent basis; It has to be done in VB.NET 2003
Left by Madhuri on Apr 23, 2011 9:26 PM

# GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hi,
This is the good running code for freshers.
Left by Abhay Malviya on Apr 30, 2011 11:30 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I havent got answer to my query till date.
Left by ferhat syed on May 09, 2011 3:42 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
The name 'UpdateOrAddNewRecord' does not exist in the current context
Left by siva on Jun 23, 2011 3:17 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Fetch Error:Line 1: Incorrect syntax near '('.e current context
Left by siva on Jun 23, 2011 6:10 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
please help in this error clear Fetch Error:Line 1: Incorrect syntax near '('.
Left by siva on Jun 23, 2011 6:12 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Fetch Error:Line 1: Incorrect syntax near '('.
Left by siva on Jun 23, 2011 6:13 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@siva,

Check your SQL query and make sure that you have space in between TOP and ( symbol.
Left by Vinz on Jun 23, 2011 7:16 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
thats error ok clear but another raised doesn't update data, incorrect syntax near'CompanyName'
Left by siva on Jun 24, 2011 1:32 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
please help me.. thats error ok clear but another raised doesn't update data, incorrect syntax near'CompanyName'
Left by siva on Jun 24, 2011 1:35 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Check the spacing between each fields in your UPDATE statement.
Left by Vinz on Jun 24, 2011 1:35 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
thank u reply me.. already check it but not workout same error raised...
Left by siva on Jun 24, 2011 2:32 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
this is query sqlStatement = "UPDATE addcompany" + "SET CompanyName = @CompanyName,ContactName = @ContactName," + "ContactTitle = @ContactTitle,Address = @Address,Country = @Country" + "WHERE CustomerID = @CustomerID,";
Left by siva on Jun 24, 2011 2:34 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Use this:

sqlStatement = "UPDATE addcompany SET CompanyName = @CompanyName,ContactName = @ContactName,ContactTitle = @ContactTitle,Address = @Address,Country = @Country WHERE CustomerID = @CustomerID";
Left by Vinz on Jun 24, 2011 3:36 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
very very thanks.. u work perfect...
Left by siva on Jun 24, 2011 4:34 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Left by siva on Jun 30, 2011 1:05 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
another one grid view develop but error raised in Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition.
Left by siva on Jun 30, 2011 1:11 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
error this part if (dt.Rows.Count > 0)

{

GridView1.DataSource = dt;

GridView1.DataBind();

}
Left by siva on Jun 30, 2011 1:15 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
@siva,

The error seems to be very logical.. That means that if you are binding your GridView manually in your code then remove the DataSourceID you assigned in your GridView in the ASPX mark up.
Left by Vinz on Jun 30, 2011 2:25 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
How do I Pass Int value as ID
I Have Int value in ID
Your code have String value..?
help me out .

THnx.
Left by kyan on Jul 02, 2011 8:44 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
excellent peace of work perfect code
Left by Taha Ashraf on Jul 04, 2011 2:53 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
can u give me example of inserting values inside grid view,not adding externel textboxes
Left by mani on Jul 26, 2011 12:36 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
thanks for it. but it's can't clear the concept of user. so please show clear example.
Left by Rohit Tripathi on Jul 28, 2011 1:34 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Its very clear,simple and understandable to the freshers also. I am using "GridView1.Rows[e.RowIndex].Cells[0].Text " for getting id to update gridview. It's taking "" value. But it have to take "1/number". I already changed the ID into Integer.Pls help me.Its very urgent to me ........
Left by Satish on Aug 10, 2011 3:36 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Please post your gridview mark up so that I can take a look. I want to see how your column is constructed.
Left by Vinz on Aug 10, 2011 5:25 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
But what about if I want to make one of them a dropdownlist instead of having all of them as textbox, assume that there is a field with limited options, how do I do that sir? thank you
Left by Randel Ramirez on Sep 08, 2011 12:45 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Thank u.....
Its Really good........
Left by Bhuvana on Sep 15, 2011 1:15 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Thanks.... i have solve my problem .... u have given step by step ,its really helpful
Left by Jay on Sep 23, 2011 3:48 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Dude! Awesome,Even I understood(I suck at coding) this article.I owe you.
Left by Sudarshan Srinivasan on Sep 27, 2011 10:53 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
it's really good article.. thanks duddy..
Left by Murali on Oct 14, 2011 1:01 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Nice article. it's really helpful and understandable. Thanks for sharing with us.
Here is also a nice one article on Insert, Update, Delete datagridview, you may check this url for more details...
http://www.mindstick.com/Articles/30148105-6777-467a-9ecc-82a2118387d0/?Insert%20Update%20Delete%20Records%20in%20CSharp%20.NET

Thanks
Left by Tito on Oct 15, 2011 9:12 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hello,

very nice example and it is very useful. Thanks a ton for this.

I am using the same gridview and above the grid view i am having text boxes, instead editing in the gridview i would like to display all values in my textboxes clicking on edit button of gridview.

I am using below lines to do the same.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
string id = GridView1.Rows[e.RowIndex].Cells[0].Text; //ID
string company = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; //Company

}

but getting error for RowIndex which is as below. your help will be highly appreciated.

error is:
Error 1 'System.Web.UI.WebControls.GridViewEditEventArgs' does not contain a definition for 'RowIndex' and no extension method 'RowIndex' accepting a first argument of type 'System.Web.UI.WebControls.GridViewEditEventArgs' could be found (are you missing a using directive or an assembly reference?)

Thanks in advance.

Regards,
Viquar Ahmed
Left by Viquar Ahmed on Oct 19, 2011 10:28 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Nice article, help a lot
Left by Rishi Sanuj on Oct 21, 2011 7:33 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
the text retrieved is not the new value but the old one

string fName = ((TextBox)users_grd.Rows[e.RowIndex].Cells[2].Controls[0]).Text; ;
string lName = ((TextBox)users_grd.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
Left by N on Oct 26, 2011 7:03 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
This is good....
Left by ramu on Oct 28, 2011 6:52 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
hey . its a nice article...really very simple and good
Left by Ravinder on Nov 03, 2011 10:45 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Great article but id we need to set auto increment
Left by jigensh on Nov 06, 2011 1:16 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
thanks for sharing
Left by peddiraju on Jan 01, 2012 10:41 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
this article understanding easy......
Left by Avinash Varshney on Jan 03, 2012 11:46 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Hello...

Super Example....i have an output super sir...
Left by Prabakaran on Jan 06, 2012 7:48 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
This was a great help. Thx
Left by Stuart on Jan 15, 2012 5:16 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
hi friends
in windows form how to Insert,Edit,Update and Delete the data from the grid view.
Left by suresh on Feb 03, 2012 10:43 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Thanks to geeksblog.. I m a beginner so its great helful for me .. The problem come from UPDATE Statement [Error is New line constant I remove the plus sign and quotes after that it works properly] Thank u once again
Left by Bhuvan on Feb 14, 2012 11:15 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I m in a big problem in grdview i m trying to edit it throw command text ="edit" and insert vale on text box with save btnsave click..
i m try if textbox insert vale are fill in gridview if btnsave click and if we wandt to edit it then on the same btnsave it save updated data
Left by shoaib on Mar 24, 2012 3:20 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
use this for resolve updating error
sqlStatement = "UPDATE Customers SET CompanyName = @CompanyName,ContactName = @ContactName,ContactTitle = @ContactTitle,Address = @Address,Country = @Country WHERE CustomerID = @CustomerID";
Left by jignesh on Apr 21, 2012 1:05 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
excellent tutorial,thank you very much
Left by sateesh on Apr 24, 2012 11:31 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
Thank you so much for this great tutorial!

But, my update command isn't being executed? When i edit and click on update, it doesn't update anything. Can someone tell me what I'm doing wrong?

sqlStatement = "UPDATE allmovies SET title = @title,company = @company,director = @director,editor = @editor WHERE id = @id";
Left by Junit on Apr 27, 2012 4:28 PM

# update command not working
Requesting Gravatar...
hi vinz,
my code for update command is
public void update(string name, string email, int phone)
{
using (SqlConnection con = new SqlConnection(@"Data Source=SATEESH\SQLEXPRESS;Initial Catalog=demo;Integrated Security=True"))

{
con.Open();

string str = "UPDATE register SET name = @name,email = @email WHERE phone = @phone";



using (SqlCommand cmd = new SqlCommand(str, con))

{
cmd.CommandType = CommandType.Text;

cmd.Parameters.AddWithValue("@name", name);

cmd.Parameters.AddWithValue("@email", email);

cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(phone));



cmd.ExecuteNonQuery();

}

}

}
and ROW UPDATING EVENT IS AS FOLLOWS

string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[1]).Text;
string email = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[1]).Text;

int phone =

Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[3].Text);

update(name, email, phone);

GridView1.EditIndex = -1;

bindgridview();
plz help me. update command is not working also it is not showing any error ,i guess something is wrong with the update command syntax.
in my tables phone is primary key
Left by sateesh on Apr 28, 2012 9:15 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
in the above code ,
controls of all are at zero only type error, and my cells of [1],[2],[3],are correct
Left by sateesh on Apr 28, 2012 9:27 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
hi
frnd,
i m little confused with the concept of gridview..we are required to rebind gridview after rowediting event..if we do not bind it again then we have to click twice on edit button to run this event...why? what is exactly happening?
plz explain..
Left by ravi on Jun 09, 2012 3:24 AM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
i am using query base update in gridview but its not working and not showing any kind of and its not working plz help me

string id = GridView1.Rows[e.RowIndex].Cells[0].Text;
string name =((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string city = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
//SqlCommand cmd = new SqlCommand("update customer set cname='" + name + "',address='" + address + "',city='" + city + "' where cid='" + id + "'",obj.con);
//cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
Response.Redirect("customer.aspx");
gridbind();
Left by shoaibsaleem on Dec 04, 2012 6:10 PM

# re: GridView Insert, Edit, Update and Delete – The Ado.Net way
Requesting Gravatar...
I got problem while editing data using dropdownlist can u help?
Left by salina on Feb 18, 2013 1:10 AM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net | Join free