Devils Work

—Blog By DotNetRuler

GridView Row Edit, Delete and Update

Posted by DotnetRuler on March 27, 2009


In this Post I am going to explain a simple light weight GridView Edit, Delete, and Update functionality.  We are going to apply this functionality on Northwind Database, Employee table.

Following are the screen shots.

normal-vieweditmodeview

 

First of all I am going to explain about creating a Connection String.

Connection String has mainly 3 properties.

DataSource — DataSource is your SQL Server name.

Initial Catalog — Your Database name (Northwind in this case).

Integrated Security – True

Integrated Security will access the SQL Server with the current windows identity established on the Operating System. For more information about Integrated Security refer this. We usually place the connection string in the Web.config file under “Configuration ==> ConnectionStrings” section.

Here is my connection string.

<connectionStrings>

 

    <add name=NorthwindConnectionString connectionString=Data Source=*****(SQL Server Name);Initial Catalog=NorthWind;Integrated Security=True;/>

  </connectionStrings>

To learn more about different type of connection strings refer this.

Then, after we are done with your connection string in the Web.config file let’s move on to the C# code.

The Following Snippet is to bind GridView.

private void BindGridData()

  {

    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString))

      {

          conn.Open();

          using (SqlCommand comm = new SqlCommand(“select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))

          {

               SqlDataAdapter da = new SqlDataAdapter(comm);

               DataSet ds = new DataSet();

               da.Fill(ds);

               GridView1.DataSource = ds;

               GridView1.DataBind();

          }

      }

  }

The First Line using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object’s resources. Refer this for Complete Reference.

The following is how we write asp.net GridView web server control code in aspx page.  I guess most of the people will be aware of the GridView events. For complete Reference refer this.

In the Code you can see I put AutoGenerateColumns=”false”. That means I have to write column names whatever I want to show to the user. If we put AutoGenerateColumns=”True”, that means u don’t have to write any custom code on your page and user can see each and every column in your dataset or datatable whatever you are binding to your gridview.

It is always good to have some control on these instead of giving up everything to it. I want to hide EmployeeID   for the user.  But I need it for querying the databse while updating and deleting  the user stuff.  So

How can we hide a column in a GridView and access it in the Code behind ?

We can do this in several ways!!! , But depends on what column we want to hide. I always follow this method.

Writing a Template Field and making it invisible.  In the template field I will Place a label or some controls, So that it’s very easy to access those controls in the code behind by using FindControl method.

Suppose if we are trying to hide primary key of our table, there is actually no need to hide. GridView has a Property called DataKeyNames. We have to give our primary key column name to it. It will do the rest.  we can see how we can access that in the code behind in the GridView_Rowupdating Event which I am going to explain later part of this article.

What is TemplateField, ItemTemplate, and EditItemTemplate?

We will use Template Field, whenever we want to define some custom control in the data bound controls like GridView, DataGrid or DataRepeater.

ItemTemplate is the content to display for the items in the TemplateField. 

EditItemTemplate as the name itself it is the content to display for the items in the TemplateField when it is in Edit mode. Refer this for complete reference.

Take this simple Snippet.

<asp:TemplateField HeaderText=”LastName”>

     <ItemTemplate>

            <asp:Label runat=”server” ID=”LastName” Text=’<%#Eval(“LastName”) %> />

     </ItemTemplate>

     <EditItemTemplate>

          <asp:TextBox runat=”server” ID=”txtLastName” Text=’<%#Eval(“LastName”) %> />

          <asp:RequiredFieldValidator runat=”server” ID=”rfdLastName”                                       ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />

     </EditItemTemplate>

</asp:TemplateField>

 

In the above Snippet you are seeing a label in Item Template that means whenever we are showing GridView to the user Label will be visible to the user. If he clicks edit (or) in the edit mode he can be able to see the Textbox.

<asp:BoundField HeaderText=”FirstName” DataField=”FirstName” ReadOnly=”false”/>

The above piece of code will also do the same as label in ItemTemplate and Textbox in the EditItemTemplate. By default all the boundfields will be trasferred as Textboxes in Edit Mode. To avoid this we need to keep the property ReadOnly as false, Then in the edit mode nothing will happenes. It just visible like a label.

 

The reason I use TemplateField instead of BoundField is that, it is very easy to grab those controls in the codebehind if we user labels or textboxes. In case of the bound field’s we need to check what column it is and need to use index of that cloumn, which is little hard and even in future if we change the column order  we have to change the code too.

 

<asp:GridView ID=”GridView1″ runat=”server” GridLines=”None” AutoGenerateColumns=”false”

      AlternatingRowStyle-BackColor=”#EEEEEE” EditRowStyle-BorderColor=”Red”

      onrowcancelingedit=”GridView1_RowCancelling” onrowcommand=”GridView1_RowCommand”

      onrowdeleting=”GridView1_RowDeleting” onrowediting=”GridView1_RowEditing”

      onrowupdating=”GridView1_RowUpdating” DataKeyNames=”EmployeeID”>           

      <Columns>           

         <asp:TemplateField Visible=”false” HeaderText=”EmployeeID”>

            <ItemTemplate>

              <asp:Label runat=”server” ID=”EmployeeID” Text=’<%#Eval(“EmployeeID”)%> />

            </ItemTemplate>

         </asp:TemplateField>

         <%–<asp:BoundField HeaderText=”FirstName” DataField=”FirstName” />–%>

 

         <asp:TemplateField HeaderText=”LastName”>

 

            <ItemTemplate>

              <asp:Label runat=”server” ID=”LastName” Text=’<%#Eval(“LastName”) %> />

            </ItemTemplate>

 

            <EditItemTemplate>

            <asp:TextBox runat=”server” ID=”txtLastName” Text=’<%#Eval(“LastName”) %> />

            <asp:RequiredFieldValidator runat=”server” ID=”rfdLastName”                    ControlToValidate=”txtLastName” ValidationGroup=”var1″ ErrorMessage=”*” />

            </EditItemTemplate>

 

         </asp:TemplateField>

         <asp:TemplateField HeaderText=”Title”>

 

            <ItemTemplate>

              <asp:Label runat=”server” ID=”Title” Text=’<%#Eval(“Title”) %> />

            </ItemTemplate>

 

            <EditItemTemplate>

              <asp:TextBox runat=”server” ID=”txtTitle” Text=’<%#Eval(“Title”) %> />

              <asp:RequiredFieldValidator runat=”server” ID=”rfdTitle”                       ControlToValidate=”txtTitle” ValidationGroup=”var1″ ErrorMessage=”*” />

            </EditItemTemplate>

 

         </asp:TemplateField>

 

         <asp:TemplateField HeaderText=”Country”>

        

           <ItemTemplate>

             <asp:Label runat=”server” ID=”Country” Text=’<%#Eval(“Country”) %> />

           </ItemTemplate>

 

           <EditItemTemplate>

             <asp:TextBox runat=”server” ID=”txtCountry” Text=’<%#Eval(“Country”) %> />

             <asp:RequiredFieldValidator runat=”server” ID=”rfdCountry”                 ControlToValidate=”txtCountry” ValidationGroup=”var1″ ErrorMessage=”*” />

           </EditItemTemplate>

 

          </asp:TemplateField>

 

      <asp:TemplateField HeaderText=”Action”>

 

      <ItemTemplate>

      <asp:LinkButton ID=”btnEdit” Text=”Edit” runat=”server” CommandName=”Edit” />

      <br />

      <asp:LinkButton ID=”btnDelete” Text=”Delete” runat=”server” CommandName=”Delete” />

      </ItemTemplate>

 

      <EditItemTemplate>

      <asp:LinkButton ID=”btnUpdate” Text=”Update” runat=”server” CommandName=”Update” />

      <asp:LinkButton ID=”btnCancel” Text=”Cancel” runat=”server” CommandName=”Cancel” />

      </EditItemTemplate>

 

      </asp:TemplateField>

 

   </Columns>

</asp:GridView>

If you see the Last TemplateField part in the above code, I am using the link buttons for edit, update, delete and cancel. May be you may think why am I using link buttons as we are provided with some command field buttons by GridView.

1)      If we use command buttons we have less control on them while doing validations, i.e. while assigning validation groups.

2)      Secondly if you want to include a custom field (some button or link) in the same column it’s not possible.

If we use proper command names for the buttons like “EDIT”, “DELETE”, “UPDATE”, “CANCEL” these will also trigger the appropriate GridView Events.

Ok let’s move on to Code behind what we have to do when user clicks Edit, Delete, Update and Cancel

When we click on Edit the OnRowEditing event will be fired. You can see the C# code below

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

   GridView1.EditIndex = e.NewEditIndex;

   BindGridData();

}

In the above code snippet as you see GridViewEditEventArgs will give the row number whatever you are editing by NewEditIndex property. So GridView will put the appropriate row into the Edit Mode by assigning row number to its EditIndex property. Then again we have to call that BindGridData () method to bind data for the textboxes.

So once after done with editing data, if we click update the following method will be triggered. It will call OnRowUpdating Event.  

1)      The First line is to get the Primary Key of the table using DataKeyNames Property of GridView.

2)      The Second line is to access the value of the invisible column.

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

   string s = GridView1.DataKeys[e.RowIndex].Value.ToString();           

   Label EmployeeID = GridView1.Rows[e.RowIndex].FindControl(“EmployeeID”) as Label;

   TextBox LastName = GridView1.Rows[e.RowIndex].FindControl(“txtLastName”) as TextBox;

   TextBox Title = GridView1.Rows[e.RowIndex].FindControl(“txtTitle”) as TextBox;

   TextBox Country = GridView1.Rows[e.RowIndex].FindControl(“txtCountry”) as TextBox;

   String UpdateQuery = string.Format(“UPDATE Employees SET LastName='{0}’,

                        Title='{1}’,Country='{2}’ WHERE EmployeeID = {3}”,LastName.Text, Title.Text, Country.Text, Convert.ToInt32(EmployeeID.Text));

 

    GridView1.EditIndex = -1;

    BindGridData(UpdateQuery);

}

Once we access the required fields in the code behind, we need to update the data in the database and show the updated data to the user. So am calling the method BindGridData method which is overloaded . I am passing Update Query as a parameter to it. You can see that method in the following snippet.

private void BindGridData(string Query)

{

  string connectionstring  =        ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

 

  using (SqlConnection conn = new SqlConnection(connectionstring))

  {

    conn.Open();

    using (SqlCommand comm = new SqlCommand(Query +

                  “;select E.EmployeeID,E.FirstName,E.LastName,E.Title,E.Country from Employees E”, conn))

    {

        SqlDataAdapter da = new SqlDataAdapter(comm);

        DataSet ds = new DataSet();

        da.Fill(ds);

        GridView1.DataSource = ds;

        GridView1.DataBind();

    }

  }

}

If the user click cancels the following event (OnRowCancelling) will be fired. When you are setting the value of the EditIndex to -1 that means you are exiting from the editmode.  So i.e. when user clicks cancel, here we are exiting from the editmode and rebinding the data to the GridView by calling BindGridData method.

protected void GridView1_RowCancelling(object sender, GridViewCancelEditEventArgs e)

{

    GridView1.EditIndex = -1;

    BindGridData();

}

If the user clicks the Delete button OnRowDeleting event will be fired. The following is the code for that event. Going into that code we are trying to get the primary key of the employee table(EmployeeID) by using GridView DataKeyNames and then  pass the Query to the BindGridData method to bind the updated data to the GridView.

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

    string EmployeeID = GridView1.DataKeys[e.RowIndex].Value.ToString();

    string Query = “delete Employee where Employee.EmployeeID = “ + EmployeeID;

    BindGridData(Query);

}

 

Happy Coding .

Keep Rocking as always J

DotNetRuler. 

About these ads

58 Responses to “GridView Row Edit, Delete and Update”

  1. mudassarkhan said

    Nice post!!! keep posting

    Mudassar Khan

  2. adilahmed1 said

    You can post code of how to add new record in gridview also

  3. warangal said

    Hi
    Nice post dotnetruler
    can u also post details of about gridview events with examples and when we use such events
    and how to add new record in gridview

  4. mark simmons said

    Hi, Nice post and very clearly written.
    I’m new to asp.net and have a gridview app in which I want to update an image field with a fileupload control based replacement but don’t see how to get the sql update to take the new image value. I’m using the built in update of the gridview so maybe that is making things difficult. My image is stored as varbinary(MAX) and displaying the image is done via an itemtemplate to invoke my image handler to write to the response output. That part works well for the small number of records I need to show. Yes, I know it could be done by just storing the image path and using the server’s filesystem for image file but I really don’t want to do that in this situation. Any thoughts on how an image update in the gridview could be achieved in this scenario?

  5. mark simmons said

    Thanks for the comment. I already know how to upload images (from my own add image form and the upload control) and show existing images in the grid. I’m doing that just fine right now. What I was asking for is a way to have the grid editable such that as well as editing in text boxes it will allow me to edit/change the image from the db (via some upload code) and then use the grid’s own update to do its sql update. I can view images in the grid but without the grid doing the actual update of a image just as it does transparently for, say, integers or text then I cannot see how the grid is useful in my scenario. It seems that what I need is some ‘hook’ I can code against when it does its own update. I could then supply the image bytes at this point. Maybe there isn’t a way to have it do this after all ?

    – Mark

  6. Ulrike said

    Thank you for this article and information. You brought the solution to me and it works fine! My endless search ends now :o)

  7. Adam said

    Nice post, but your delete command is vulnerable to SQL Injection attacks. It needs parameterized queries or a stored procedure instead.

  8. Jodhpur said

    Nice post!!! keep posting

  9. amen said

    Hi nice post, but i have some probleme in my updating method , when i try de catch the value of my textbox i can’t have any value !! it’s null by default !!! I don’t know why and I want to ask you what do you think to use e.newValues[gridView.DataKey.dataKeysnames] ? thanks

    • this is my guess for your problem.. You might be binding the grid again in the Pageload or some where before the RowUpdating event being called. So if you bind the grid before the event being called. gridview goes to normal mode(I mean not in the edit mode). You can access the GV textboxes when it is in the edit mode.

      You can use e.NewValues also, but i always prefer to access each and every control using find control method. If you used to this coding practice it helps you changing the value in the onrowdatabound event or some other GV events. You can see the use of it my coming article.

    • RedSkull said

      hi, i happens the same thing, this lose the new values of the textbox. this is my code, thanks.

      My Code

      • I saw your code. its looks good.. i would appreciate if you post your full .cs code. I doubt you are binding the grid in the page load event and when ever you hits update, again page load happens so grid is getting the values from the database.. so what ever the values you entered in the edit mode are going away. If my assumption is right, then bind the grid only for the first page load by writing if(!Page.IsPostback)
        {
        // Bind the Grid
        }

        If my assumption is wrong, then post me your full .cs code. I can help you

      • RedSkull said

        Hi, dude you have all the reason, this was the binding in the page_load. I fixed the problema, thanks dude.

  10. RedSkull said

    Hi, I have a problem, i can’t filter the gridview with dropdownlist, i think what the razon is the (!IsPostBack) for binding the gridview(it’s have rowupdating and more events). I hope you can help me.

  11. RedSkull said

    Hi, i can’t filter yet the gridview with dropdownlist, i think what the razon is the (!IsPostBack) for binding the gridview(it’s have rowupdating and more events). I hope you can help me. thanks.

  12. Gregory said

    very good, thx!

  13. stephen said

    its really a gr8 article.. thanks.. keep it up

  14. Hi,
    I don’t think that in case of TemplateFields, RowUpdating event handler is able to give the NewValues being updated.
    Please confirm.

    Thanks,
    Munish Bansal

  15. YoursTruly said

    Awesome man! awesome! this article is so clean and easy to understand and use. Thanks!!

  16. ieda said

    this is my code..this code can’t update the data in gridview..pls somebody help me..

    Private Function GenerateUpdateQuery() As String

    Dim i As Integer = 0
    Dim tempstr As String = “”
    Dim temp_index As Integer = -1

    Dim TableName As String = DirectCast(Session(“TableSelected”), String)
    Dim Query As String = “”

    Query = “Update ” & TableName & ” set ”

    For i = 1 To Table.Columns.Count – 1

    If Not i = 5 Then

    Select Case Table.Columns(i).DataType.Name

    Case “Boolean”, “Int32″, “Byte”, “Decimal”
    If DirectCast(ParameterArray(i), String) = “True” Then
    ParameterArray(i) = “1”
    ElseIf DirectCast(ParameterArray(i), String) = “False” Then
    ParameterArray(i) = “0”
    End If

    If i = Table.Columns.Count – 1 Then
    Query = (Query + Table.Columns(i).ColumnName & “=”) + ParameterArray(i)
    Else
    Query = (Query + Table.Columns(i).ColumnName & “=”) + ParameterArray(i) & “, ”

    End If

    Exit Select

    Case “String”, “DateTime”

    If DirectCast(ParameterArray(i), String).Contains(“‘”) Then
    tempstr = DirectCast(ParameterArray(i), String)
    ParameterArray(i) = DirectCast(ParameterArray(i), String).Replace(“‘”, “””)
    temp_index = i
    End If

    If i = Table.Columns.Count – 1 Then
    Query = (Query + Table.Columns(i).ColumnName & “='”) + ParameterArray(i) & “‘ ”
    Else
    Query = (Query + Table.Columns(i).ColumnName & “='”) + ParameterArray(i) & “‘, ”
    End If

    Exit Select

    End Select

    End If
    Next

    If temp_index > -1 Then
    ParameterArray(temp_index) = tempstr
    End If
    If Table.Columns(0).DataType.Name = “String” OrElse Table.Columns(0).DataType.Name = “DateTime” Then

    Query = ((Query & ” where “) + Table.Columns(0).ColumnName & ” = “) + ParameterArray(0) ‘& “‘”
    Query = ((Query & ” and “) + Table.Columns(5).ColumnName & ” = ‘”) + ParameterArray(5) & “‘, ”

    Else

    Query = ((Query & ” where “) + Table.Columns(0).ColumnName & ” = “) + ParameterArray(0) ‘& ” ”
    Query = ((Query & ” and “) + Table.Columns(5).ColumnName & ” = ‘”) + ParameterArray(5) & “‘, ”

    End If

    Return Query

    End Function

  17. Leif said

    Just wanted to say very cool and very informative! Thank you for taking the time and publishing such a great example!
    Leif

  18. Vikram said

    Good..
    But it cnt solve my problem…

  19. Satish said

    Its very excellent Example of Gridview.

    But In my code update doesnot work.

    Magic is when i put break point every values gets affected as soon as i rebind it it displays old values.

    I used if(!IsPostBack()) also in page load.

    Any Help in this regard?

  20. Siju said

    In ur above rowediting code i don’t want to rebind the data but i want editing controls once i clicked Edit button. I’m trying to do that but editing controls are displayed after second time click in Edit button.Help e to find this.

    • First of all, you have to bind the grid in the roweditingevnt. Because, Viewstate changes after the edit event.

      Not sure why it is firing for second time. with out seeing code i can not help you, sorry.

  21. Isleme said

    Thanks a lot !! Good Job !

  22. Sebastian said

    Good Job!!!! It is really helpful…Keep it Up

  23. sudhanshu said

    Very nice post and very nicely explained

  24. [...] GridView Tags: Categories: Actions: E-mail | Kick it! | Permalink | Kommentare (0) | Comment RSS Ähnliche BeiträgeHow to store files in a SQLServer Database using ASP.NETStoring FilesASP.NET – Google like Suggest Box Link Comparing AD custom classes to AccountManagement ASPNETDB There are two other ways for de…Building and Running ASP.NET Applications  ASP.NET Integration with IIS 7 How to Capture ASP.NET Page Trace Events in IIS 7.0 Tra… Über den Author.Net, Silverlight & more Search TagsSQLServer SP2 Windows Firewall Archiv2011April (68)März (92)Februar (42)Januar (34)2010Dezember (13) Seiten-ÜbersichtBeispiel SeiteSeite 1 Blogroll Al NyveldtSudokuKids gets an upda…SudokuKids+ update is l…To update or not to upd… Download OPML file RecentPostsASP.NET – Multiple File UploadIIS – Database ManagerWPF CommandingPhysics engineASP.NET MVC3 Tools UpdateTroubleshooting HTTP-500 ErrorsSharepoint – Development setupSQLServer – connection stringsMVC Intranet ApplicationSQLExpress – the underlying provider failed to open [...]

  25. [...] http://devilswork.wordpress.com/2009/03/27/gridview-row-edit-delete-and-update/ –> Pend [...]

  26. dhavapriya said

    nice post.. Thank u…

  27. ARUL said

    hai

  28. Shikha said

    Thanx so much…

  29. A sagar said

    I am beginner, i have coded a web site which has a master page and content page. I have put two textboxes in content page, 1 as “ID” and other is “Name”. But i am trying to put the “submit” button in master page , which has has to common for all content pages of master page. How to work on this. Please help.
    Thank You in advance

  30. ArfaniDude said

    That Was A Great Code And Iy Realy Helped Me alot
    But Please Can Anyone Tell Me How To Add More Records Directly In To Grid
    Thnx

  31. Bharat said

    this is easily undarstand code
    nice post
    i understand many thing from this post

  32. Matt Roy said

    First, thanks for this entire post, it helped me to remember.

    Then, I had to program the “Adding a Row” part. So here is how I did it. Since I’m in VB.NET, my code is in VB.NET… And my code is for GridView using Paging, so, I add the Row as the first row in the first page.

    1) Put the DataSet global instead of local to BindGridData.
    Public ds AS DataSet = New DataSet

    2) In BindGridData, I clear the global DataSet before filling it:
    ds.Clear
    ‘Then
    da.Fill(ds)
    ‘….
    3) Then a button to add dynamically a Row and enter into editing mode for this row.
    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
    GridView1.PageIndex = 0 ‘In my case, I use Paging, so I return to 1st page.
    BindGridData() ‘Reload the GridView to fill the global Dataset “ds”
    Dim MyNewRow As DataRow = ds.Tables(0).NewRow() ‘Creating the row.
    ‘Whatever you want to initialize the Row:
    MyNewRow(0) = “Something” ‘If String
    MyNewRow(1) = False ‘If Boolean
    ‘…
    ‘Adding the Row to the DataSet
    ds.Tables(0).Rows.InsertAt(MyNewRow, 0) ‘Adding at beginning (index 0)
    ‘ –> ds.Tables(0).Rows.Add(MyNewRow) ‘If you want to add at the end
    GridView1.EditIndex = 0 ‘Index of new row to edit (0 if added at beginning of GridView)
    GridView1.DataSource = ds ‘Re-assign the dataset to the GridView
    GridView1.DataBind() ‘Re-bind.
    End Sub

  33. kevin said

    Thanks a lot. nice pose.

  34. Simba said

    Excellent post…Would it be possible to get a full copy of the.cs code behind? I seem to be getting some errors. Thanks.

  35. Basheer said

    Updating is not working. From texboxes only old values retrieved for update, Y?

  36. [...] GridView Row Edit, Delete and Update « Devils WorkMar 27, 2009 … Hi, i can’t filter yet the gridview with dropdownlist, i think what the razon is the (! IsPostBack) for binding the gridview(it’s have rowupdating and … [...]

  37. Jasper said

    Why is property GridView1.OnRowCommand set?

    • If you have multiple actions like “Download file”, “Export to excel”, “Export to PDF”, “Edit” , “Update”, “Delete” etc…..

      when the user makes an appropriate action, the code behind needs to know what action user was performed.. all these actions will be handled in the OnRowCommand event.

  38. sateesh said

    hi ,
    i got some problem with my update event.
    my update query is like this
    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 like this

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

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

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

    update(name, email, phone);

    GridView1.EditIndex = -1;

    bindgridview();

    in my table phone is primary key.plz help me.no error nothing coming

  39. udara said

    this is the error i got when i handled RowUpdating event

    ” Server Error in ‘/’ Application.

    Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.”

    Please help me to solve this error

  40. policy said

    Hmm is anyone else encountering problems with the pictures
    on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog.
    Any feed-back would be greatly appreciated.

  41. popo lili said

    I got all the way to the end only to find I can’t use this…it doesn’t work without “GridView1_RowCommand.” Why is this function not included?

    • Yes, i did not include the GridView1_Rowcommand, I simply kept it as a place holder and talked about what you can do with that event.

      For Update, Delete, Cancel operations, you do not need rowcommand as we have separate events already pre-defined by gridview.

      If you want to do more customization then only you need row command.

  42. Nayana dewangan said

    tell me how to insert , retrieve, update, delete information with images in asp.net grid view in c#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 30 other followers

%d bloggers like this: