.NET Discussion

.NET Issues, Problems, Code Samples, and Fixes

ASP.NET: GridView Update/Edit/Cancel, HyperLinkFields, and DataKey Retrieval


Today was spent mostly tackling the GridView’s Update/Edit functionality, and I got incredibly frustrated, at first. This was my first foray into this part of the GridView’s functionality, since I haven’t really had to develop anything using it since the switch to 2.0, as everything in DataGrids still functioned fine. With a little bit of research, a lot bit of patience, and some help from the internet community, I was able to solve all my issues, and pretty elegantly at that.

Basically, I was trying to convert an existing data-display-only GridView (ie, no special functions) into one where I can update a field, namely the inventory for displayed products. After working with DataGrids so efficiently, I was scared that GridViews were going to be a million times more complex. I suppose my eyes got big when I saw all the new properties and methods, and wanted to try them all out.  Big mistake.

Most articles I found were for hardcoded datasources (especially on MSDN, ugh) and didn’t really help me much, so this post will be referring to GridViews with dynamically bound datasources. First, create a GridView with three bound columns and an Update/Edit/Cancel (CommandField) column:

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False" onrowediting=GridView1_RowEditing datakeynames="productid" onrowcancelingedit=GridView1_RowCancelingEdit onrowupdating=GridView1_RowUpdating>
       <columns>
       <asp:hyperlinkfield datanavigateurlfields="productid" datanavigateurlformatstring="/products/index.aspx?productid={0}" text="Product" target="_blank" />
        <asp:boundfield datafield="inventory" headertext="Inventory" />
        <asp:commandfield showeditbutton="True" />
        <asp:boundfield datafield="productid" visible="false" />
       </columns>
      </asp:gridview>

Nothing in there should be shocking to anyone: all your events are handled, you have a HyperLinkField that uses the DataNavigateURLFields property to insert a ProductID, and you have set your DataKeyNames property to your hidden field which holds your ProductID.

Because we are not using the GridView’s built-in data model and are binding dynamically, the GridView will not switch into and out of Edit Mode automatically. Thus, in order to switch it into Edit Mode, in each of your event handles (RowEditing, RowUpdating, and RowCancelingEdit) you must do two things:

  1. Change the GridView’s EditIndex appropriately
  2. Re-bind your GridView

These are both very easy to do, and your RowEditing and RowCancelingEdit handles should be simple, like this: 

Protected Sub GridView1_RowEditing(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)

GridView1.EditIndex = e.NewEditIndex 'set to selected row
BindGridView() ' your own subroutine that you use to bind your datagrid

End Sub

Protected Sub GridView1_RowCancelingEdit(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)

GridView1.EditIndex = -1 'set to no selection
BindGridView()

End Sub

One issue I ran into while attempting to figure this all out was if I didn’t rebind my GridView at the end of each event, I was required to click twice to get it to select the correct row, and if I clicked around, it would always be a row behind. So be sure to rebind your GridView at the end of your event handler. 

The RowUpdating event is where it gets tricky, since pulling values is not necessarily intuitive. You can’t do something like GridView1(i)(j).Text = str or anything even close. Instead, you must cast the cells as controls. Here’s an example of how I did it in my RowUpdating event handler:

Dim name As HyperLink
Dim inv As TextBox

name = CType(GridView1.Rows(e.RowIndex).Cells(0).Controls(0), HyperLink)
inv = CType(GridView1.Rows(e.RowIndex).Cells(1).Controls(0), TextBox) ' .Cells(1) refers to the 2nd column

Once you’ve casted them, you can now easily get their values by invoking their .Text property, ie, name.Text. Remember that my first column was a HyperLinkField, so in order to pull that value, I must cast that column as a HyperLink.

Finally, to pull your hidden value that you’ve dubbed a DataKey in the GridView’s DataKeyNames property, do the following:

Dim ProductID as Integer = GridView1.DataKeys(e.RowIndex).Value

EDIT 3/5/08: I forgot to mention in this article how to retrieve “Read-Only” data. You cannot convert a read-only cell into a textbox, so you must retrieve the value another way:

Dim str as String = GridView1.Rows(e.RowIndex).Cells([your cell]).Text

Then do whatever you need to do to update your database, set the EditIndex to -1, and call your BindGridView() subroutine. Everything should be sorted out when the “Update” link is pressed. To enhance this process, be sure to include your GridView in an AJAX UpdatePanel.

Hope this saves someone a full day of research (and possibly some hair)!

kick it on DotNetKicks.com

About these ads

September 26, 2007 - Posted by | AJAX, ASP.NET, GridView, Tips & Tricks

148 Comments »

  1. Thanks – was having a few problems trying to find examples without using hardcoded data sources. This has been very useful – rest easy in the knowledge you have made someone’s day easier!

    Comment by Matt Fisher | September 28, 2007 | Reply

  2. Good, glad I could help :) It was just so strange to me that everywhere I looked I found only examples of hardcoded data sources. Who uses hard coded data sources? Not this guy.

    Comment by Some.Net(Guy) | September 28, 2007 | Reply

  3. your explanation was simple and clear. never using the gridview control before, i was nervous about trying to do this. but with you example, it was simple. i really want to thank you for your time spent putting this up on the web.

    thanks a million

    Comment by Dan Benjamin | October 19, 2007 | Reply

  4. @Dan –

    You’re welcome :) Thanks for the comment!

    Comment by Some.Net(Guy) | October 19, 2007 | Reply

  5. Can you please upload small text file with code?
    Which will really help everybody.

    Rana

    Comment by Rana | October 23, 2007 | Reply

  6. This was a really useful example.
    Just one minor problem when casting, I receive the following error:

    Unable to cast object of type ‘System.Web.UI.LiteralControl’ to type ‘System.Web.UI.WebControls.TextBox’.

    Any ideas?

    Comment by LG | November 21, 2007 | Reply

  7. LG –

    Make sure that you are trying to cast the correct objects! I don’t know how you got a literal control in your GridView, but make sure that everything is parallel. For instance, here:

    Dim inv As TextBox

    inv = CType(GridView1.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)

    notice how I create inv as a TextBox and I’m casting the control in column 2 (which is actually .Cells(1).Controls(0)) as a TextBox. You may have something trying to cast a textbox as a literal, or vice versa. Make sure they match.

    Comment by Some.Net(Guy) | November 21, 2007 | Reply

  8. here is what I am trying to do. The error still persist….Just not too sure what else to look for….

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    ‘ get the cart from the Session object
    Dim cart As Hashtable = CType(Session(“cart”), Hashtable)
    ‘ create a table to hold the item
    dataTable.Columns.Add(New DataColumn(“drug_id”, GetType(String)))
    dataTable.Columns.Add(New DataColumn(“drug_name”, GetType(String)))
    dataTable.Columns.Add(New DataColumn(“drug_price”, GetType(Decimal)))
    dataTable.Columns.Add(New DataColumn(“Quantity”, GetType(Int32)))
    dataTable.Columns.Add(New DataColumn(“subtotal”, GetType(String)))

    ‘ Populate the table with items from cart
    Dim de As DictionaryEntry
    For Each de In cart
    Dim shoppingItem As Item = CType(de.Value, Item)
    Dim dr As DataRow = CreateNewDataRow(shoppingItem)
    dataTable.Rows.Add(dr)
    Next de
    ‘ get a databindable view of the datatable that can be sorted, etc
    CartView = New DataView(dataTable)
    CartView.Sort = “drug_name” ‘ sort items by name
    If Not IsPostBack Then
    BindGrid()
    End If

    End Sub

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

    Dim name As TextBox
    Dim price As TextBox
    Dim quantity As TextBox
    Dim drugid As TextBox
    Dim subtotal As TextBox

    name = CType(GridView1.Rows(e.RowIndex).Cells(0).Controls(0), TextBox)
    price = CType(GridView1.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
    quantity = CType(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)
    drugid = CType(GridView1.Rows(e.RowIndex).Cells(3).Controls(0), TextBox)
    subtotal = CType(GridView1.Rows(e.RowIndex).Cells(4).Controls(0), TextBox)

    BindGrid()

    End Sub

    Comment by LG | November 22, 2007 | Reply

  9. LG –

    Post your .aspx HTML GridView code, too. Maybe that will help.

    Comment by Some.Net(Guy) | November 22, 2007 | Reply

  10. Here is the code behind the gridview.

    <asp:TextBox ID=”TextBox1″ runat=”server” BackColor=”White” BorderStyle=”None” ReadOnly=”True”
    Text=” Width=”136px”>

    <asp:Label ID=”Label2″ runat=”server” Text=”>

    <asp:TextBox ID=”TextBox2″ runat=”server” BackColor=”White” BorderStyle=”None” ReadOnly=”True”
    Text=” Width=”64px”>

    <asp:Label ID=”Label3″ runat=”server” Text=”>

    <asp:TextBox ID=”LtxtQuantityGO” runat=”server” MaxLength=”99999″ Text=”
    Width=”64px”> 

    <asp:Label ID=”Label1″ runat=”server” Text=”> 

     <asp:TextBox ID=”TextBox3″ runat=”server” BackColor=”White” BorderColor=”White”
    BorderStyle=”None” ReadOnly=”True” Text=” Width=”64px”> 

    <asp:Label ID=”Label4″ runat=”server” Text=”>

    <asp:TextBox ID=”TextBox4″ runat=”server” BackColor=”White” BorderColor=”White” BorderStyle=”None”
    ReadOnly=”True” Text=” Width=”96px”>

    <asp:Label ID=”Label5″ runat=”server” Text=”>

    Comment by LG | November 22, 2007 | Reply

  11. LG –

    Where’s the GridView? This is just random text boxes and labels…

    Comment by Some.Net(Guy) | November 22, 2007 | Reply

  12. Sorry, disregard the last….hopefully this will post ok.

    <asp:TextBox ID=”TextBox1″ runat=”server” BackColor=”White” BorderStyle=”None” ReadOnly=”True”
    Text=” Width=”136px”>

    <asp:Label ID=”Label2″ runat=”server” Text=”>

    <asp:TextBox ID=”TextBox2″ runat=”server” BackColor=”White” BorderStyle=”None” ReadOnly=”True”
    Text=” Width=”64px”>

    <asp:Label ID=”Label3″ runat=”server” Text=”>

    <asp:TextBox ID=”LtxtQuantityGO” runat=”server” MaxLength=”99999″ Text=”
    Width=”64px”> 

    <asp:Label ID=”Label1″ runat=”server” Text=”> 

     <asp:TextBox ID=”TextBox3″ runat=”server” BackColor=”White” BorderColor=”White”
    BorderStyle=”None” ReadOnly=”True” Text=” Width=”64px”> 

    <asp:Label ID=”Label4″ runat=”server” Text=”>

    <asp:TextBox ID=”TextBox4″ runat=”server” BackColor=”White” BorderColor=”White” BorderStyle=”None”
    ReadOnly=”True” Text=” Width=”96px”>

    <asp:Label ID=”Label5″ runat=”server” Text=”>

    Comment by LG | November 22, 2007 | Reply

  13. I guess not, somewhere it is truncating

    Comment by LG | November 22, 2007 | Reply

  14. Again, no GridView :( You can email me at fixmysite.please[at]gmail if you want to.

    Comment by Some.Net(Guy) | November 22, 2007 | Reply

  15. Sent…Thank you.

    Comment by LG | November 22, 2007 | Reply

  16. LG –

    I think I know why! You have some of your textboxes set to readonly=True. Remove that and try again.

    Comment by Some.Net(Guy) | November 22, 2007 | Reply

  17. :( no luck

    Comment by LG | November 22, 2007 | Reply

  18. hmm…it may have something to do with the fact that you’re using templatefields instead of boundfields. create another gridview using boundfields (don’t delete this one!) and wire it up to what you have now. i think the only reason you’re using template fields anyways is for sizing reasons. in templatefields, i believe you have to use the “findcontrol” method to locate the textboxes.

    example:

    Dim t As New TextBox
    t = CType(GridView.SelectedItem.FindControl(“TextBox1″), TextBox)

    Try that and see if it works!

    Comment by Some.Net(Guy) | November 22, 2007 | Reply

  19. Thank you. I have re-created the gridview with boundfields this time, and it works fine.
    While in edit mode, how do I prevent some of the fields from being edited. I have tried to make them read only, but that does not work…any ideas?

    Comment by LG | November 22, 2007 | Reply

  20. i’m getting error:

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

    when i try to update my shopping cart gridview:

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

    Dim name As TextBox
    Dim price As TextBox
    Dim drugID As TextBox
    Dim currQty As TextBox
    Dim subtotal As TextBox

    drugID = CType(NGVCartRG.Rows(e.RowIndex).Cells(0).Controls(0), TextBox)
    name = CType(NGVCartRG.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
    currQty = CType(NGVCartRG.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)
    price = CType(NGVCartRG.Rows(e.RowIndex).Cells(3).Controls(0), TextBox)
    subtotal = CType(NGVCartRG.Rows(e.RowIndex).Cells(4).Controls(0), TextBox)

    BindGrid()

    End Sub

    do you have an idea of what i’m doing wrong?

    thanks!

    Comment by NRGMS | November 25, 2007 | Reply

  21. @LG –

    Making the fields read-only should make it so they cannot be edited… try making them read-only via the designer’s property editor for the gridview. if that doesn’t work, send me your new aspx source code and i will take a look.

    @NRGMS –

    there are a few things that could be wrong, just by your error, because the code you posted looks fine. the error that you’re getting means either your column count is off (you have fewer columns than you think) or your row count is off (you have fewer rows than you think). when does this error actually occur? is it when the user clicks the “update” button in your gridview? if you’d like, you could send your aspx code to me at fixmysite.please[at]gmail and i’ll take a look.

    Comment by Some.Net(Guy) | November 25, 2007 | Reply

  22. Thanks. One quick question… For the update event I grab the values from the Grid but it does not get the new value typed into the text box. It gets the original value. I am trying to grab the new value so I can update the database. Did I forget something?
    thanks,
    Josh
    Code:

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

    Dim reportTitle As TextBox

    reportTitle = CType(dgChangeReportTitles.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
    Dim reportCode As String = dgChangeReportTitles.DataKeys(e.RowIndex).Value

    Dim newReportName = reportTitle.Text
    MsgBox(reportCode & “will be changed to ” & newReportName)

    ‘covera.changeReportName(reportCode, newReportName)

    Comment by Josh | December 17, 2007 | Reply

  23. Josh –

    It looks like you’ve got some reference issues. You’re calling the RowUpdating event for “GridView1″ but you’re grabbing the report title from “dgChangeReportTitles”. That’s just the first thing I noticed. Let me know if that’s your problem, or if something else is amiss.

    Comment by Some.Net(Guy) | December 17, 2007 | Reply

  24. Thanks for responding, but thats not it, I just forgot to change the names.

    When I click the edit button, the reportname field changes to a text box like its supposed to. But then if I change the reportname and click update, it stays a text box and displays the original value, not the one I just typed in. I think I’m not binding the data correctly?

    Here’s my code, let me know if anything else jumps out.
    I am calling a web service to populate the grid and I have to use another to update the DB.
    thanks,
    Josh

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Session(“SessionID”) Is Nothing Then
    covera.SessionHeaderValue = New CoveraServices.SessionHeader
    covera.SessionHeaderValue.SessionID = Session(“SessionID”).sessionid
    End If

    Dim options As CoveraServices.MessageCode() = covera.displayAllReportTitles()
    With dgChangeReportTitles
    .DataSource = options
    .DataBind()

    End With
    End Sub

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

    Dim reportTitle As TextBox

    reportTitle = CType(dgChangeReportTitles.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
    Dim reportCode As String = dgChangeReportTitles.DataKeys(e.RowIndex).Value

    Dim newReportName = reportTitle.Text
    ‘MsgBox(reportCode & “will be changed to ” & newReportName)

    covera.changeReportName(reportCode, newReportName)

    End Sub

    Protected Sub dgChangeReportTitles_RowEditing(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)

    dgChangeReportTitles.EditIndex = e.NewEditIndex ‘set to selected row
    dgChangeReportTitles.DataBind()
    ‘Dim options As CoveraServices.MessageCode() = covera.displayAllReportTitles()
    ‘With dgChangeReportTitles
    ‘ .DataSource = options
    ‘ .DataBind()
    ‘End With

    End Sub

    Protected Sub dgChangeReportTitles_RowCancelingEdit(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)

    dgChangeReportTitles.EditIndex = -1 ‘set to no selection
    dgChangeReportTitles.DataBind()
    ‘Dim options As CoveraServices.MessageCode() = covera.displayAllReportTitles()
    ‘With dgChangeReportTitles
    ‘ .DataSource = options
    ‘ .DataBind()
    ‘End With

    End Sub

    Comment by Josh | December 18, 2007 | Reply

  25. Comment by Josh | December 18, 2007 | Reply

  26. not sure how to post the .aspx

    <%–

    –%>

    Comment by Josh | December 18, 2007 | Reply

  27. Josh –

    Are you using bound fields or template fields in your gridview?

    Comment by Some.Net(Guy) | December 18, 2007 | Reply

  28. Go ahead and email me your aspx code… fixmysite.please at gmail.com

    Comment by Some.Net(Guy) | December 18, 2007 | Reply

  29. bound fields, heres code without tags

    GridView ID=”dgChangeReportTitles” runat=”server” onrowediting=dgChangeReportTitles_RowEditing onrowupdating=dgChangeReportTitles_RowUpdating datakeynames=”Code” Height=”1px” Width=”463px” AutoGenerateColumns=”False”

    BoundField DataField=”Code” HeaderText=”Report Code” SortExpression=”ReportCode” ReadOnly=”True” InsertVisible=”False”

    BoundField DataField=”Message” HeaderText=”Report Description” SortExpression=”ReportDesc”

    commandfield showeditbutton=”True”

    Comment by Josh | December 18, 2007 | Reply

  30. Josh, I think I know what it is. You’re not resetting the editindex to -1 before you rebind. Try that and let me know.

    Comment by Some.Net(Guy) | December 18, 2007 | Reply

  31. now I am getting an ‘index out of range’ error for:

    reportTitle = CType(dgChangeReportTitles.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)

    heres the rest of the update sub:
    Dim reportCode As String = dgChangeReportTitles.DataKeys(e.RowIndex).Value

    Dim newReportName = reportTitle.Text
    ‘MsgBox(reportCode & “will be changed to ” & newReportName)

    covera.changeReportName(reportCode, newReportName)
    dgChangeReportTitles.EditIndex = -1
    dgChangeReportTitles.DataBind()

    Comment by Josh | December 18, 2007 | Reply

  32. Josh –

    You have to set your .DataSource before you can .DataBind! :)

    Comment by Some.Net(Guy) | December 18, 2007 | Reply

  33. In fact, you need to do that on all your RowEdit/Update/Cancel event handlers…

    Comment by Some.Net(Guy) | December 18, 2007 | Reply

  34. Now I am getting ‘object not set to instance of object when I try to get the value from the text box. Is it a text box or a bound field anyway. I am not getting along with GridViews.
    thanks again. Heres more code.
    Josh

    ‘reportTitle = CType(dgChangeReportTitles.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
    reportTitle = CType(dgChangeReportTitles.Rows(e.RowIndex).FindControl(“Message”), TextBox)
    Dim reportCode As String = dgChangeReportTitles.DataKeys(e.RowIndex).Value
    Dim newReportName As String = reportTitle.Text

    Comment by Josh | December 18, 2007 | Reply

  35. Josh –

    Don’t use the .FindControl method… you will get the error you are saying you’re getting. “Message” isn’t the name of the bound field. Bound fields do not have names or IDs. Uncomment your first one, it’s correct. Here’s the process you have to follow in the RowUpdate (conceptually)

    Create textbox variable

    Cast bound field as texbox

    Pull value from casted boundfield/textbox

    Perform whatever actions you need

    Reset EditIndex to -1

    Reset your DataSource

    Rebind your GridView

    What I do when I’m having problems debugging is I will create a literal somewhere on the page and have it display whatever value I’m supposed to be retrieving while knocking every other thing out of the equation. Try doing that by ONLY pulling the reportTitle value from the GridView in your RowUpdate event, and maybe you will figure out what the problem is.

    Hope this helps!

    Comment by Some.Net(Guy) | December 18, 2007 | Reply

  36. great post, thx!

    Comment by HF | December 21, 2007 | Reply

  37. Thanks for posting the helpful article.

    Comment by GS | December 21, 2007 | Reply

  38. thanks alot you made my day !!
    I sepend day and days searching and trying to do this in so many different ways until i got confused by all the googling but still couldnt find a decent example till today ! so thanks for your help

    Comment by Eman | January 13, 2008 | Reply

  39. Great, thanks :) Glad I could help!

    Comment by Some.Net(Guy) | January 13, 2008 | Reply

  40. Hey!

    I’m glad I quickly came upon your page, as I was about to take a plunge into cooking my own custom updating methods. Thanks a lot man!
    :D

    Comment by Jorge Sanchez | January 14, 2008 | Reply

  41. I’ve got an interesting question:

    What if instead of showing the words “Edit/Update/Cancel” I want it to show something like “Change/Do it/Bail out!”?

    Further more, what if I want to have images showing instead of the words?

    Comment by Jorge Sanchez | January 16, 2008 | Reply

  42. Okay… sorry… silly me… EditImageUrl, CancelImageUrl, EditText :S

    Sorry for wasting a few Kb’s on your database! Thanks anyway :D

    Comment by Jorge Sanchez | January 16, 2008 | Reply

  43. haha, no worries Jorge… that’s what this site is here for. Have you not seen my whole post where I wonder how to connect two projects? Hoo boy…

    Comment by Some.Net(Guy) | January 17, 2008 | Reply

  44. Hey great post, looking for something like this for a long time.
    However I’m having a problem with the rowupdating
    I’m getting the old values. I looked at Josh’s post but i think mine is a diff issue.
    after I press update the txtbox DOES contain the new value but in the update event i receive the old values.

    I’m posting the code

    dsQuizTableAdapters.tblQuestionsTableAdapter taQuestions;
    dsQuizTableAdapters.tblQuizTableAdapter taQuiz;
    dsQuiz ds;
    protected void Page_Load(object sender, EventArgs e)
    {
    //manual connection
    string conString = “DRIVER={MySQL ODBC 3.51 Driver}; SERVER=www.xxxx.com;” +
    “DATABASE=quiz; UID=xxxx; PASSWORD=xxxxx; OPTION=3″;
    System.Data.Odbc.OdbcConnection odbcCon = new System.Data.Odbc.OdbcConnection(conString);
    System.Data.Odbc.OdbcDataAdapter odbcDa = new System.Data.Odbc.OdbcDataAdapter(“SELECT * from quiz”, conString);
    DataTable dtQuiz = new DataTable();

    ds = new dsQuiz();
    taQuiz = new dsQuizTableAdapters.tblQuizTableAdapter();
    taQuestions = new dsQuizTableAdapters.tblQuestionsTableAdapter();
    GridViewQuestions.RowEditing += new GridViewEditEventHandler(GridViewQuestions_RowEditing);
    GridViewQuestions.RowUpdating += new GridViewUpdateEventHandler(GridViewQuestions_RowUpdating);

    taQuiz.Fill(ds.tblQuiz);
    DDLquiz.DataSource = ds.tblQuiz;
    DDLquiz.DataValueField = “id”;
    DDLquiz.DataTextField = “name”;
    if(!IsPostBack)
    DDLquiz.DataBind();

    loadQuestions(1);

    }

    void GridViewQuestions_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    System.Web.UI.WebControls.TextBox t = (System.Web.UI.WebControls.TextBox)GridViewQuestions.Rows[e.RowIndex].Cells[0].Controls[0];
    System.Web.UI.WebControls.TextBox t2 = (System.Web.UI.WebControls.TextBox)GridViewQuestions.Rows[e.RowIndex].Cells[1].Controls[0];

    }

    void GridViewQuestions_RowEditing(object sender, GridViewEditEventArgs e)
    {
    Response.Write(“edit”);

    //GridView GridViewQuestions =(GridView)(sender);
    GridViewQuestions.EditIndex = e.NewEditIndex;
    GridViewQuestions.DataBind();
    Response.Write(e.NewEditIndex);
    }
    private void loadQuestions(int quizID)
    {
    taQuestions.FillByID(ds.tblQuestions,quizID);
    GridViewQuestions.DataSource = ds.tblQuestions;

    GridViewQuestions.DataBind();

    }

    and ASP

    Comment by shooks | January 28, 2008 | Reply

  45. Shooks –

    It appears as though you’re doing nothing in your RowUpdating event except assigning variables. You need to update your database and then rebind your GridView.

    Hope this helps!

    Comment by Some.Net(Guy) | January 28, 2008 | Reply

  46. Thanks for the quick reply :) Yeah in the debugger i’m checking the values of t and t2 and i’m getting the old values

    Comment by shooks | January 28, 2008 | Reply

  47. Shooks –

    It appears that even though you are databinding, you’re not resetting the DataSource property in your RowEditing event. This may be leading to old values appearing.

    This should put you on the right track!

    Comment by Some.Net(Guy) | January 28, 2008 | Reply

  48. It looks like every postback refills the dataset from the database. I guess i need to use session variables, I hope it will work.
    Thanks a bunch!!!!

    Comment by shooks | January 28, 2008 | Reply

  49. Shooks –

    You shouldn’t have to use session variables. What exactly are you trying to do, and maybe I can help you figure it out?

    Comment by Some.Net(Guy) | January 28, 2008 | Reply

  50. I’m trying to fill my dataset according to a selection.
    right now its hardcoded “loadQuestions(1)” this function uses a tableadaptor to fill my “questions” dataset table.

    now I simply connect the GridView’s datasource to that dataset “questions” table and use the built-in edit button. I capture the events as shown in the code.

    I’m guessing that each time the page posts back it runs the “loadQuestions(1)” and therefor it “refreshes” the dataset with the sql query. thats why I thought I needed session variables to hold the dataset and to fill it only once.

    btw I’m connecting to a mysql database.

    Comment by shooks | January 28, 2008 | Reply

  51. Ok – I have some forms that perform similar operations. To avoid getting your old data, you need to make sure that you update your table based on the new input BEFORE the RowUpdating event is called, because, yes, every time an event occurs, the page runs through the complete lifecycle in order. You can check the IsPostBack variable to run some more logic to make sure the correct loadQuestions(x) is being run.

    Let me know if you need anything else!

    Comment by Some.Net(Guy) | January 28, 2008 | Reply

  52. I got it sorted out with the dataset stored in a session variable and ispostback logic.
    Thanks for your help and quick replies.

    untill next time ;)

    Comment by shooks | January 28, 2008 | Reply

  53. next time came quick :S
    for some reason when I update the row it doesn’t change the values of the row in the dataset, kind of makes binding useless. Am I doing something wrong?

    Comment by shooks | January 29, 2008 | Reply

  54. If you’re not binding it to something pulled directly from the database (ie, something pulled from a session variable), you need to make sure that you update both your database and your other data source BEFORE you complete your RowUpdating event. I had this problem when I was using Generics bound as a datasource; I updated my DB but not my object, and since the object was bound to the GridView and not my DB, it didn’t appear updated, even though it was.

    Hope this helps!

    Comment by Some.Net(Guy) | January 29, 2008 | Reply

  55. nice one

    Comment by love | February 8, 2008 | Reply

  56. really i would like to thanks you……
    I want to join dotnetdiscussion group.
    plz add me or tell me what i have to do to add here and join discussion.

    Thanks & Regards
    S.N.Patel

    Comment by shiv narayan patel | February 15, 2008 | Reply

  57. i wrote the same code for updating but when i press update button ,an exception fires up and tells me that datakeys index is negative , i don’t know , what is my mistake

    Comment by nastaran | February 15, 2008 | Reply

  58. nastaran –

    post your code here (with your .aspx) and i’ll take a look. remember to escape your left angle bracket characters (&lt;)

    Comment by Some.Net(Guy) | February 15, 2008 | Reply

  59. here is the code i wrote
    protected void GridViewPackage_RowEditing(object sender, GridViewEditEventArgs e)
    {
    GridViewPackage.EditIndex = e.NewEditIndex;
    databind();
    }
    protected void GridViewPackage_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
    GridViewPackage.EditIndex = -1;
    databind();
    }
    protected void GridViewPackag_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    //this line has problem
    int index =Convert.ToInt32(GridViewPackage.DataKeys[e.RowIndex].Value);
    updatesatements;
    databind();

    }

    Comment by nastaran | February 15, 2008 | Reply

  60. nastaran –

    did you declare what your datakeys were in your aspx code?

    <asp:gridview id=”GridView1″ runat=”server” datakeynames=”yourdatakeyfield”>

    also, did you declare more than one field to be a datakey? if you did, there’s a slightly different syntax for getting the datakey value.

    Comment by Some.Net(Guy) | February 15, 2008 | Reply

  61. i define the datakeynames and i have just one datakey

    Comment by nastaran | February 15, 2008 | Reply

  62. hmmm…. i don’t see anything obvious…is it possible that your data cannot be converted into an integer? although that wouldn’t explain the negative index. is your debugger telling you it’s breaking at that point? if you want, send your .aspx and your .aspx.cs file to fixmysite.please [at] gmail.com and i’ll take a closer look.

    Comment by Some.Net(Guy) | February 15, 2008 | Reply

  63. I have similar reqirement for the GridView and were not able to find a solution for a while on the web until I found this one.(Update/Cancle no show on clicking Edit). Thanks very much for the frustration relief.

    Comment by Renay | February 18, 2008 | Reply

  64. Thanks very much for this, a straightforward example detailing the functions of the GridView.

    This article was the one out of many that really helped. Thanks again!

    Comment by Daren | February 27, 2008 | Reply

  65. hello
    i have a repeater i have a table
    this table contains some data , and the header and number of columns in the table change depend on some condition ?
    can anybody help me?

    Comment by nastaran | February 27, 2008 | Reply

  66. Nastaran –

    Try to modify this code snippet for your purposes:

    For i As Integer = 0 To [some number or upperbound(0)]

    If [some condition] Then

    GridView1.Columns(i).HeaderText = [some text]
    GridView1.Columns(i).Visible = True

    Else ‘make unused fields invisible

    GridView1.Columns(i).Visible = False

    End If

    Next

    Hopefully this points you in the right direction :)

    Comment by Some.Net(Guy) | February 27, 2008 | Reply

  67. no i have a repeater not a gridview
    inside a repeater i have a table

    Comment by nastaran | February 27, 2008 | Reply

  68. how do you form your table? is it manually (ie, forming tr/td tags) or object-oriented (ie, creating table, table row, and table cell objects)?

    Comment by Some.Net(Guy) | February 27, 2008 | Reply

  69. it’s table object ()

    Comment by nastaran | February 27, 2008 | Reply

  70. Not sure you still see these but am getting ‘… argument out of range …’ error. Am trying to dynmicaly create update statement (needs additional coding, I know). Some items are read-only in the gridview. Code below. Thoughts?

    Protected Sub gvResults_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvResults.RowUpdating
    Dim strUpdCmd As String = “”
    Dim intX As Integer = 0
    Dim txtTemp As New TextBox
    Dim x As String = “”

    strUpdCmd = “UPDATE TBLWORESCHED SET ”
    For intX = 1 To gvResults.Rows(e.RowIndex).Cells.Count – 1 ‘Already know the first cell is the edit cell
    ‘x for testing
    x = “rows ” & gvResults.Rows.Count.ToString & “, ” & _
    e.RowIndex.ToString & ” and cells ” & gvResults.Rows(e.RowIndex).Cells.Count.ToString & _
    “, ” & intX.ToString
    txtTemp = CType(gvResults.Rows(e.RowIndex).Cells(intX).Controls(0), TextBox)
    If txtTemp.ReadOnly = False Then
    strUpdCmd = strUpdCmd & txtTemp.Columns.ToString & ” = ” & txtTemp.Text
    End If
    Next

    gvResults.EditIndex = -1
    SqlDataSource1.SelectCommand = ViewState(“SqlSelect”)
    gvResults.DataBind()

    End Sub

    Comment by dczimmer | March 4, 2008 | Reply

  71. Donald –

    I think you’re messing up in the “txtTemp.Columns.ToString”. That will only get you how many columns are in your textbox that you have dynamically created in memory. So essentially, if your textbox has 20 columns (20 characters allowed, I think is the default) you’re trying to set 20 = [whatever text is in the box], which should throw some sort of error.

    Let me know if that fixes your problem.

    Comment by Some.Net(Guy) | March 4, 2008 | Reply

  72. Thanks for the quick response. I’ve learned more about the gridview in this thread than I have in 2+ days searching the internet. Thanks again.

    I commented the line out and still get the error. I should have been clearer as the error is being thrown at:

    txtTemp = CType(gvResults.Rows(e.RowIndex).Cells(intX).Controls(0), TextBox)

    Comment by dczimmer | March 5, 2008 | Reply

  73. Ah, ok it all makes sense now. You cannot convert a “read-only” item into a textbox, because it does not turn into a textbox! The way you retrieve read-only information is

    value = GridView1.Rows(e.RowIndex).Cells([cell number]).Text

    Try that and tell me if that helps!

    Comment by Some.Net(Guy) | March 5, 2008 | Reply

  74. I’ll give it a try. My debugger is acting up. A thought, when the row goes to update mode does the cell index change by the number ‘functions’ (update, cancel) available? Example cell 0 was Edit and cell 1 was (first bound data cell). In update is both Update and Cancel in cell 0?

    Comment by dczimmer | March 5, 2008 | Reply

  75. It is a readonly issue. I had my column count wrong. Is there a way to eval if the cell is readonly and bypass it? Otherwise I am going to hard code the edited cells. Thanks again.

    Comment by dczimmer | March 5, 2008 | Reply

  76. Donald –

    In response to comment 74, no, the index stays the same. As for checking to see if a cell is readonly, maybe check the Enabled property? I haven’t tested it, so I can’t say for sure, but it may work. You could also do a “Try…Catch” where if casting throws an error, assume it’s readonly, but this is not the correct solution, just a way to do it.

    Comment by Some.Net(Guy) | March 5, 2008 | Reply

  77. Hi it’s nice to have ur code. but i have a problem, for the update event Iam taking the values from the Grid but it does not get the new value typed into the text box. It gets the original value. I am trying to get the new value so I can update the database. Did I forget something?
    thanks,

    Comment by Persis | March 6, 2008 | Reply

  78. Persis-

    What’s your RowUpdating event look like?

    Comment by Some.Net(Guy) | March 6, 2008 | Reply

  79. Sorry to bother you again. The following conditions apply. VS2005 using Oracle data provider (10.x) for .NET. I have a search page that limits what the user can request. The intent was to dynamically build the query to get the data based on what the user provides using like’s, and’s, and between’s; again depending on the user enters. On the called page is a gridview with a SQLDatasource configured for the Oracle .NET data provider.

    The SQLDataSource has only a Select command with no WHERE clause, no SelectParameters, and no UPDATE, INSERT, or DELETE commands (or parameters). On page_load I get the values from the previous page then append the custom created where clause to the SelectCommand, do a viewstate on the new select command, then do a databind on the gridview and the data is there. My _rowediting and _roweditingcancel contain a reference to the rowed in edit mode (or -1), a setting of the SelectCommand to the saved viewstate entry and the gridview databind. All is good.

    Then I do an update. The _rowupdating generates an update statement based on the values populated from the gridview (thanks again for your code) not using parameters but coding the statement. SQLDataSource updatestatement is set and the SQLDataSource update function called. The editing index is set back to -1, the SelecetComand is set to the viewstate variable and the gridview databind is called.

    The database update occurs (as evidenced by looking in the database). The databinding event is throwing an ORA-01036: illegal variable name/number. I suspect thru much, much searching that there is a parameter binding/typing issue but I can not figure out where to look. Or, I am completely out to lunch …. Any assistance would be appreciated.

    Comment by dczimmer | March 6, 2008 | Reply

  80. Donald –

    I’ll be honest, I don’t have much experience with Oracle databases; I typically use MySQL. However, from the error code “ORA-01036″ it appears that it is an error thrown from your database, not from your code, although the result of the error is undoubtedly in your code. What I would do is create a literal or label or something and instead of updating your database, set your literal to the SQL string generated for when you would typically update your DB. You may find your problem in there.

    If not, without seeing code, I can’t be of much more assistance.

    Hope this helps!

    Comment by Some.Net(Guy) | March 6, 2008 | Reply

  81. Can I send you the code? My email is provided above.

    Comment by dczimmer | March 6, 2008 | Reply

  82. Sure, send it to fixmysite.please[at]gmail.com

    Comment by Some.Net(Guy) | March 6, 2008 | Reply

  83. [Comment 77]
    Hi, this is RowUpdating event code
    Dim inv As TextBox

    inv = CType(ViewStatus.Rows(e.RowIndex).Cells(2).Controls(1), TextBox)
    Dim StatusID As Integer = ViewStatus.DataKeys(e.RowIndex).Value
    MsgBox(inv.Text)

    ViewStatus.EditIndex = -1
    ViewStatus.DataSource = posDet.getStatus
    ViewStatus.DataBind()

    ”But this code gives me the Old value not the New Value
    help me out

    Comment by Persis | March 6, 2008 | Reply

  84. Persis –

    Your old value will continue to appear in your gridview until you update the source. It looks like all you’ve done is take the value and put it in a textbox, but not done any storing of the value. Also, are you sure that it’s the second control (.Controls(1))? If it’s a bound field, the control index will always be 0. The only time it would be different is if it is a template field.

    Hope this helps shoot you in the right direction!

    Comment by Some.Net(Guy) | March 7, 2008 | Reply

  85. u r right, but b4 updating the datasource iam trying to get the eidted text from the textbox to update the datasource.But it returns the old value only.And there’s nothing wrong with the (.Controls(1)).
    ”This is the update statement
    MsgBox(inv.Text)
    UpdateStatus(StatusID, inv.Text)
    ”Refersh the source again
    ViewStatus.EditIndex = -1
    ViewStatus.DataSource = posDet.getStatus
    ViewStatus.DataBind()

    Thanks yaar.

    Comment by Persis | March 8, 2008 | Reply

  86. Persis –

    I do believe that you should not be using .Controls(1). If your column is a bound column, you will never use .Controls(1), and if your column is a template control, you will have to use a different method to capture your data (.FindControl). Try using .Controls(0), unless you can explain why you are using .Controls(1). I just can’t see why you would.

    Comment by Some.Net(Guy) | March 10, 2008 | Reply

  87. ”Thanks again, this is the Source Code

    <asp:Label ID=”Statuslbl” runat=”server” Text=”>

    <asp:TextBox ID=”StatusName” runat=”server” Text=”>

    ”Help me to get the new values

    Comment by Persis | March 11, 2008 | Reply

  88. Inside the template field, the first control is Label and second control is TextBox and for the Text Property iam binding the Bind(“StatusName”)

    Comment by Persis | March 11, 2008 | Reply

  89. My values were disappearing on PostBack too, so I worked around it by using the old school Request.Form call.

    Turns out I’d made a really rookie mistake in my Page Load call and was filling the data on every postback and not just on the first page load. As a result my amended valuse were getting over written before the RowUpdating method executed.

    What a dullard… hopefully this will help someone else… if not you can at least have a giggle at my expense!

    Comment by Kathryn | April 3, 2008 | Reply

    • [Comment 89]
      Thanks very much for posting, Kathryn! I was doing exactly the same thing and couldn’t figure it out til reading your comment! Much appreciated.

      A fellow dullard!

      Comment by Mike | March 12, 2010 | Reply

  90. How to get the values of gridview cells in
    a button click event when the grid view contains both boundfields and template fields

    Comment by malik | June 19, 2008 | Reply

  91. plz help any one ,its urgent

    in advance thnx

    Comment by malik | June 19, 2008 | Reply

  92. Oh my god… I have been trying to figure this out for ALL DAY. I have been skimming books, Googling, testing… nothing worked, until I found this! This article is GREAT!

    Comment by Troy Campbell | July 4, 2008 | Reply

  93. Troy –

    Thanks for the comment! I’m glad I could help :)

    Comment by Some.Net(Guy) | July 7, 2008 | Reply

  94. This is very usefull article

    I want to know, how can we Update just the row of a gridview with new values from edit mode , without the data base been updated.

    Thanks

    Comment by Hammad | July 18, 2008 | Reply

  95. Hammad –

    Unfortunately your GridView is bound to your database, so any data you display is pulled directly from there. It doesn’t have its own “internal memory”, if you will. Sorry, and thanks for the comment!

    Comment by Some.Net(Guy) | July 18, 2008 | Reply

  96. Hey,

    When I click update my new values don’t appear on the row after postback. Through debugging i know the values are being stored in their respective textbox values. I take it that I need to write code to actually do the updating other than the GridView1_Updating sub. Could someone lay out how this could be done? Also, i am slightly lost on the purpose of the DATAKEY and if this could be explained i would be happy as well. do not hesitate to be explicit, as i am fairly daft in this environment. My code for the edit/updating is below. A world of thanks, in advance.

    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles GridView1.RowEditing
    GridView1.EditIndex = e.NewEditIndex

    CompleteFill()

    End Sub

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

    Dim idx As Integer
    Dim cell As DataControlFieldCell
    Dim testInt As Integer
    Dim code As TextBox
    Dim plabel As TextBox
    Dim blabel As TextBox
    Dim comm As TextBox
    Dim ID As Integer

    code = CType(GridView1.Rows(e.RowIndex).Cells(8).Controls(0), TextBox)

    plabel = CType(GridView1.Rows(e.RowIndex).Cells(9).Controls(0), TextBox)
    blabel = CType(GridView1.Rows(e.RowIndex).Cells(10).Controls(0), TextBox)
    comm = CType(GridView1.Rows(e.RowIndex).Cells(11).Controls(0), TextBox)

    GridView1.EditIndex = -1

    CompleteFill()

    ‘ Dim commie As String = comm.Text

    End Sub

    Protected Sub GridView1_RowCancelingEdit(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit

    GridView1.EditIndex = -1 ‘set to no selection
    CompleteFill()

    End Sub

    Comment by Ben | July 21, 2008 | Reply

  97. Ben –

    It appears as though you are doing almost everything right. First, I don’t know what your CompleteFill() sub does, but I assume it rebinds your GV. Second, in your RowUpdating, assuming that your respective columns in your GV are textbox columns, you are correctly pulling the values. However, you are doing nothing with those values after you pull them! Once you get your plabel, blabel, comm values, then what? You probably want to put them into your database.

    As for datakeys, they are useful for storing the ID of whatever your records are in your GV. For instance, if you have products, make a bound column for your ProductID and set visible=False, then set your ProductID as your GV’s datakey. That way you can easily pull your ProductID via the code:

    Dim ProductID as Integer = GridView1.DataKeys(e.RowIndex).Value

    without having to worry about what cell it’s in or casting it to a control. I find it very useful and easy to work with.

    Hope this helps!

    Comment by Some.Net(Guy) | July 21, 2008 | Reply

  98. Hey, Thanks for the article!!!
    I have a question, it may be a little out of the scope of this article but help me if you can.

    I have a page with a GridView with edit/delete/add
    The gridview loads a Control in a new row(under) the row that was clicked on. I do this in the rowdatabound event. What happens now is the row is in edit mode and a new gridview (with edit/delete/add) is loaded under this row. Now when I click on edit on the loaded control’s girdview everything works fine the page loads and in the databound event it checks to see the row state, if its in edit mode it loads the control, but for this to work I need to bind the parent gridview on page load. So now If i want to update the parent Row (the one that was clicked and loaded the control underneath it) It binds on pageload before it updates… so it always reverts to the old values. I tried many things to fix this… but no luck…
    There is no way for me to check in the page_load of the parent page what was clicked… if its the update button of the parent control or an edit/update button of the child control so I cannot apply the databind selectively.

    Its a little confusing, I hope you understand….

    Thanks

    T.

    Comment by T. Ski | July 22, 2008 | Reply

  99. T –

    Honestly I don’t really get what you’re trying to do, but whatever it is may be more difficult than what you need! From what I gather about what you’re doing, you may just want to convert your form into a Master/Child format, where your GV is the Master and when clicked, it pulls up editable details in the Child form (which could be another GV or a series of textboxes and a submit button). Sorry I can’t be of much more help, but I’d need to see a bit of code.

    Hope this helps!

    Comment by Some.Net(Guy) | July 22, 2008 | Reply

  100. Thanks for the quick response…
    I’m loading a usercontrol because i know no other way to insert a new row into a gridview where i can control the column span… i’m trying to do this (i’ll use ascii art to demonstrate)

    |–|–|–|
    |——–|
    |–|–|–|

    so the top row was clicked and opened a new row (with column span 3 in this case) in this row i’m loading a userControl that takes as a parameter the rowid that was clicked and displayes the relevant gridview.

    Can this Master/child format accomplish the same result?

    Comment by T. Ski | July 22, 2008 | Reply

  101. T –

    Gotta love ASCII art :) I see what you’re trying to do, and it still seems overly complex… Just have a Master form with a “Select” button that when it is clicked, it puts the Master form into “Selected” mode for that row and transfers the ID of that row to a Child form which pulls up all the relevant info. Of course I don’t know the purpose of the form, so maybe you really need to do what you’re doing, but I can’t see how it would be imperative that you do.

    If you need more info, let me know and I’ll give you some more concrete examples.

    Comment by Some.Net(Guy) | July 22, 2008 | Reply

  102. This Master/Child is new to me… sounds interesting.
    What i’m trying to do is a little different than what you describe. What happens when the (parent) row is clicked is that it turns editable (so fields of the row can be modified and updated) at the same time the child row (that contains another gridview) is loaded and rows in this new gridview can be edited as well.

    I will demonstrate with a good example (and the actual use of this model).
    Basically its a quiz with many questions, so the first page that loads contains all the questions(in a GV). When you click to edit a question you get another GV with question options that can be edited as well
    (question = Do i know .net?, question options = Yes, No).

    If this Master/Child Model you are describing can handle this UI I would love to get more information about it, please refer me to some good sources.

    Thank You

    Comment by T. Ski | July 22, 2008 | Reply

  103. T –

    I think I have found an article that is doing what you are trying to do, or at least should point you in the right direction:

    http://www.codeguru.com/columns/vb/article.php/c12647/

    Let me know how that works out for you!

    Comment by Some.Net(Guy) | July 22, 2008 | Reply

  104. Thank you very much!!!
    This article is very helpful.

    Not often do we meet people willing to help without asking for anything in return.

    peace be upon you

    T

    Comment by T. Ski | July 22, 2008 | Reply

  105. My pleasure, T! If you really want, you could buy me a beer :) Good luck w/your app!

    Comment by Some.Net(Guy) | July 22, 2008 | Reply

  106. Thanks For your Reply.
    I have a data table which is fiiling values in Gridview and i want to EDIT Those values, which is not Connected to Dsta base at all , these values are been taking by users and then inserted in data bases.

    Comment by Hammad | July 22, 2008 | Reply

  107. Hammad –

    If you want values to be reflected when you edit them, you must update the source. Updating just the data in the GV but not updating the source is like taking a freshly cut circular cookie and changing it into a star shape and then expecting your next cookie to come out looking like a star. You need to update the cutter! Your GV will continue to display whatever values there are in your datatable. The only thing I can think of is to create a datatable in memory and draw your values from that, but that’s getting really complex with determining which is your datasource.

    Hope this makes sense!

    Comment by Some.Net(Guy) | July 23, 2008 | Reply

  108. Actually i have Created a Datatable, and the Update is working in a way that when Update Button is clicked is add new row in the grid view , rather Updating the Selected row.

    Please Also Tell me how can i delete a row from grid view , which is fiiling from datatable,and not with database.

    Comment by Hammad | July 23, 2008 | Reply

  109. Hi, I posted in #97, and was answered in #98, but am still horribly lost. the response given is below in the quote boxes. The gist is that I have tried since that day to put the values for those variables into my excel file but am failing at every turn. I would appreciate if someone could show me exactly what it is i should be doing, because everything i research on the internet does not apply to me. I have copied my code in the code brackets and added the response in the quote brackets below to make things easier.

    Hey,
    
    When I click update my new values don’t appear on the row after postback. Through debugging i know the values are being stored in their respective textbox values. I take it that I need to write code to actually do the updating other than the GridView1_Updating sub. Could someone lay out how this could be done? Also, i am slightly lost on the purpose of the DATAKEY and if this could be explained i would be happy as well. do not hesitate to be explicit, as i am fairly daft in this environment. My code for the edit/updating is below. A world of thanks, in advance.
    
    Protected Sub GridView1_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs) Handles GridView1.RowEditing
    GridView1.EditIndex = e.NewEditIndex
    
    CompleteFill()
    
    End Sub
    
    Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles GridView1.RowUpdating
    
    Dim idx As Integer
    Dim cell As DataControlFieldCell
    Dim testInt As Integer
    Dim code As TextBox
    Dim plabel As TextBox
    Dim blabel As TextBox
    Dim comm As TextBox
    Dim ID As Integer
    
    code = CType(GridView1.Rows(e.RowIndex).Cells(8).Controls(0), TextBox)
    
    plabel = CType(GridView1.Rows(e.RowIndex).Cells(9).Controls(0), TextBox)
    blabel = CType(GridView1.Rows(e.RowIndex).Cells(10).Controls(0), TextBox)
    comm = CType(GridView1.Rows(e.RowIndex).Cells(11).Controls(0), TextBox)
    
    GridView1.EditIndex = -1
    
    'This is my Binding function
    CompleteFill()
    
    ‘ Dim commie As String = comm.Text
    
    End Sub
    
    Protected Sub GridView1_RowCancelingEdit(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView1.RowCancelingEdit
    
    GridView1.EditIndex = -1 ’set to no selection
    CompleteFill()
    
    End Sub

    [quote]It appears as though you are doing almost everything right. First, I don’t know what your CompleteFill() sub does, but I assume it rebinds your GV. Second, in your RowUpdating, assuming that your respective columns in your GV are textbox columns, you are correctly pulling the values. However, you are doing nothing with those values after you pull them! Once you get your plabel, blabel, comm values, then what? You probably want to put them into your database.[/quote]

    I know that the values are being retrieved into my variables but am at a complete lost as to how to get them inserted into the excel database and binded properly. no manner of explicit explanation would insult my intelligence at this point.

    I appreciate any help you all my provide.

    Thanks,

    Ben

    Comment by Ben | July 28, 2008 | Reply

  110. Ben –

    I don’t know how you are binding your site to an excel database! I assumed you were using a MSSQL or MySQL database to maintain all your data. Even an XML database would suffice, but I don’t know how to connect to an Excel DB, I’m sorry! Good luck!

    Comment by Some.Net(Guy) | July 28, 2008 | Reply

  111. i see. alas. Well I do appreciate the help. could you perhaps still post what it would take to insert values of the variables into the database after having established the CTypes. I might be able to figure it out from there. it, like obiwan, is my only hope.

    Comment by Ben | July 28, 2008 | Reply

  112. Ben –

    If you’re using a database, you need to create some sort of INSERT string to send to your DB with all your info. For instance, if you are updating a MySQL database, you could send the following string:

    INSERT INTO tblproducts (name, color) VALUES (‘widget’,’red’)

    Maybe that will send you off in the right direction!

    Comment by Some.Net(Guy) | July 28, 2008 | Reply

  113. Please Tell me how can i Change Textbox values on KeyPress event , like i have 3 textboxes, textbox1,textbox2 and textbox3 , when press tab key values from textbox 1 and 2 get added and displayed in textbox 3.

    Comment by Hammad | July 30, 2008 | Reply

  114. can you help me in generating PDF reports on the Fly in VB.net 2005.

    Comment by Hammad | August 5, 2008 | Reply

  115. Sir,
    I really surprised bcoz i m working in a small company . I am searching for an article on gridView editing and i typed i started searching in Google suddenly i switched to this site. I found tht i actually gone through this site so many times before. This is my Fav. Sir’s NagRaj (MCAD) Site..Thanq sir this site helped me a lot ..
    Small Req
    Can you send me a small article on GridView Editing ..

    ThanQ V much….

    Comment by hariprasad | August 29, 2008 | Reply

  116. Hi ,

    This is Sharma, i am not getting gridview_RowUpdating()and gridview_RowDeleting() function in Gridview asp.net2.0 with c# code. Please help me please. This is my mailID “k.sharmasvali@gmail.com”

    Thanks & Regarding
    Sharma.

    Comment by k.sharmasvali | October 28, 2008 | Reply

  117. i have a problem with the data
    in my GridView1_RowUpdating

    Dim name As TextBox
    Dim ip As TextBox
    Dim coment As TextBox
    Dim type As TextBox
    Dim str As Integer = GridView1.Rows(e.RowIndex).Cells(1).Text
    name = CType(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)
    ip = CType(GridView1.Rows(e.RowIndex).Cells(3).Controls(0), TextBox)
    coment = CType(GridView1.Rows(e.RowIndex).Cells(4).Controls(0), TextBox)
    type = CType(GridView1.Rows(e.RowIndex).Cells(5).Controls(0), TextBox)

    when i look into name.text i see the old data and not the new one

    Comment by eyal | December 17, 2008 | Reply

  118. Great idea and very simple method to update the row in datagridview. But I find that you cannot use this method for a dropdownlist in datagrid, e.g you cannot do this:
    CType(GridView1.Rows(e.RowIndex).Cells(5).Controls(0), dropdowlist). Instead I have to use this:

    CType(GridViewNotification.Rows(e.RowIndex).FindControl(“DropDownStatus”), DropDownList)

    Do you know why?

    Comment by Larry from candida diet | February 23, 2009 | Reply

  119. Larry –

    You’re correct. This is a simple example for simple databound fields. When you start getting into TemplateFields, or the only way to include dropdowns in your GridView, your method is the way to do it.

    Thanks for the comment!

    Comment by Some.Net(Guy) | February 23, 2009 | Reply

  120. thanx… it really helped me a lot.. i had wasted 1 day working on this… thanx for the solution

    Comment by ratul | March 1, 2009 | Reply

  121. Hello everyone,
    I’m trying to develop a page in ASP.net(C#) which has a gridview,a radiobutton list and a submit buttton.The procedure is like first the row should be selected then
    radio button should be selected and then submit button should be clicked.On clicking submit the column in gridview(app_status)should get updated based on userid.Datakeyname is registration_no.

    Here is the cs file I’m Unable to proceed as I getting no result and no error:

    using System;
    using System.Collections;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    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;

    public partial class munoffgui : System.Web.UI.Page
    {
    int index;
    String selid;

    protected void GridView1_RowCommand(Object sender,GridViewCommandEventArgs e)
    {

    if (e.CommandName == “Select”)

    index = Convert.ToInt32(e.CommandArgument);

    GridViewRow row = GridView1.Rows[index];

    selid = Server.HtmlDecode(row.Cells[14].Text);

    Label2.Text = selid;

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    SqlDataSource1.Update();
    }

    }

    Plz help me.It’s urgent!!!!
    Thnx in advance

    Comment by coolguy.net | March 10, 2009 | Reply

  122. Hello everyone..
    Im trying to develop a page which has gridview.It has got 3 columns. One is image.
    My problem is i cant update my database table using that. I have gone through the above posts.. Still i cant makeout.
    My probs are:
    1.I cant get the new value from the text box. It takes the old value only.So the update command updates using the old values.
    2.I want to get the fileupload fild for my image filed.
    Im using the name of the file from fileupload filed to store it in database and retriving from folder to diaplay in the gridview.

    Here is my code:

    Partial Class Administration_Default2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim ds As New Data.DataSet
    Dim da As Data.SqlClient.SqlDataAdapter
    Dim strSQL As String
    strSQL = “Select * from Category”
    Dim connString As String = “Data Source=.\SQLEXPRESS;AttachDbFilename=””|DataDirectory|\chocobar.mdf””;Integrated Security=True;User Instance=True”
    da = New Data.SqlClient.SqlDataAdapter(strSQL, connString)
    da.Fill(ds)
    ds.Tables(0).Columns.Add(“imgfile”)
    For Each tempRow As Data.DataRow In ds.Tables(0).Rows
    tempRow.Item(“imgfile”) = (“./image/” & tempRow.Item(“cat_image”))

    Next
    Grid1.DataSource = ds
    Grid1.DataBind()
    Return
    End Sub

    Protected Sub Grid1_edit(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs)

    Grid1.EditIndex = e.NewEditIndex ‘set to selected row
    Grid1.DataBind()

    End Sub

    Protected Sub Grid1_Cancel(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs)

    Grid1.EditIndex = -1 ‘set to no selection
    Grid1.DataBind()

    End Sub

    Sub Grid1_Update(ByVal Sender As Object, ByVal E As System.Web.UI.WebControls.GridViewUpdateEventArgs)

    Dim name As TextBox
    Dim str As String = Grid1.Rows(E.RowIndex).Cells(1).Text
    ‘Dim image As FileUpload
    name = CType(Grid1.Rows(E.RowIndex).Cells(0).Controls(0), TextBox)

    Dim con As New System.Data.SqlClient.SqlConnection
    Dim param As Data.SqlClient.SqlParameter
    con.ConnectionString = “Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\chocobar.mdf;Integrated Security=True;User Instance=True”
    Dim myCommand As New System.Data.SqlClient.SqlCommand
    Dim cid As Integer = Grid1.DataKeys(E.RowIndex).Value
    Response.Write(name.Text)
    param = New Data.SqlClient.SqlParameter(“@name”, Data.SqlDbType.NVarChar)
    param.Value = name.Text
    myCommand.Parameters.Add(param)
    myCommand.Connection = con
    myCommand.CommandText = “UPDATE Category SET cat_name=@name WHERE cat_id=” & cid
    Try
    con.Open()
    myCommand.ExecuteNonQuery()
    Grid1.EditIndex = -1
    Response.Write(“Category updated”)
    con.Close()
    Grid1.DataBind()
    Catch
    Response.Write(“Category not updated”)
    End Try
    End Sub

    End Class

    Pls help me.. I got deadline nearer.. Thanks in advance…

    Comment by Naveen | April 17, 2009 | Reply

  123. Test it is very usefull

    Comment by Murali | April 21, 2009 | Reply

  124. Just what I was looking for – Thanks.

    Comment by Eamonn | June 4, 2009 | Reply

  125. I don’t find this example so dynamic…
    You are creating a GridView with three, hard coded, bound columns. Or, am I missing something?

    In my code I need to populate the GridView by autogenerating the columns. The update should then handle the situation whether there are 2 or 100 columns. Is this possible?

    Comment by henrico | August 27, 2009 | Reply

  126. Henrico –

    You’re sort of right. It is not dynamic in the respect that the columns are hard-coded, yes, but it is dynamic in the respect that it’s not hard-bound to a datasource. If you need a TRULY dynamic GV, you can either turn on “autogeneratecolumns=true” or you can add columns at run-time. Something like “Gridview1.Columns.Add([your DataControlField object])” for each column in whatever datatable you have (do a “DataTable.Columns.Count” and then add as many rows as there are columns in your underlying datatable).

    Anyways, hope this helps, and thanks for your comment!
    -Jason

    Comment by Some.Net(Guy) | August 27, 2009 | Reply

  127. Thanks for your quick reply!
    I am using “AutoGenerateColumns=True”. The tricky part is how to do the Update since the database table design is vertical… Which now made me realize the impossible task to do a normal Update in GridView. Hmm, maybe a stored procedure will do the job, constructing the update command on-the-fly. I’ll try that! Thanks for your time.

    Comment by henrico | August 27, 2009 | Reply

  128. this post was super helpful. It kept me from spending too much time on the wrong path. Important to remember that when the appearance of the control changes, you have to do something different in how you access it in the controls collection for a cell.

    Comment by grant | December 28, 2009 | Reply

  129. Grant –

    Glad I could help!

    Comment by Some.Net(Guy) | December 28, 2009 | Reply

  130. You rock, dude! After hours of searching, this article gave me the solution to the double click issue I was having.

    Thanks.

    Comment by Matt | January 27, 2010 | Reply

  131. thanks for the great work.but i couldn’t get the value textbox. the textbox.text value get epty.i need to get new vale that i changed in cell. bellow have the code sample
    thank you

    Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand

    If e.CommandName.Equals(“Update”) Then

    Dim subtotal As TextBox
    subtotal = CType(GridView1.Rows(index).Cells(6).Controls(0), TextBox)

    Comment by Shashi | February 17, 2010 | Reply

  132. hi i am chhaya thanks u

    Comment by chhaya | March 4, 2010 | Reply

  133. Thank you, I had doubts about extracting a specific row from a GridView, but you helped me with : “The RowUpdating event is where it gets tricky, since pulling values is not necessarily intuitive. You can’t do something like GridView1(i)(j).Text = str or anything even close. Instead, you must cast the cells as controls.”

    Thanks !

    Comment by Rui | March 19, 2010 | Reply

  134. Hi,
    Thanks a lot for this article. Its very simple and really helpful.

    But when clicking the update button exception arises.
    So i put breakpoint in GridView2_RowUpdating.
    When the control hits the GridView2_RowUpdating the database get updated, everything works fine, but after that the control again goes to GridView2_RowUpdating and exception arises. Hope you will help me to solve this issue.

    Below is my code:

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
    PopulateGrid2()
    End If
    End Sub

    Protected Sub GridView2_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GridView2.RowCancelingEdit
    GridView2.EditIndex = -1 ‘set to no selection
    PopulateGrid2()
    End Sub

    Protected Sub GridView2_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GridView2.RowEditing
    GridView2.EditIndex = e.NewEditIndex
    PopulateGrid2()
    End Sub

    Protected Sub GridView2_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView2.RowUpdating
    id = GridView2.DataKeys(e.RowIndex).Value
    GdPname = CType(GridView2.Rows(e.RowIndex).Cells(0).Controls(0), TextBox)
    GdPSize = CType(GridView2.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
    GDPunitPrice = CType(GridView2.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)
    Try
    Product_update()
    GridView2.EditIndex = -1 ‘set to no selection
    PopulateGrid2()
    lblSuccess.Text = “That product is updated successfully”
    Catch ex As Exception
    lblError.Text = ex.Message
    End Try
    End Sub

    Private Sub Product_update()
    Dim Str As String
    Dim sqlCon As SqlConnection = New SqlConnection(strCon)
    Str = “update ProductList set ProductName='” & GdPname.Text & “‘,ProductSize='” & GdPSize.Text & “‘,UnitPrice=” & GDPunitPrice.Text & “where ProductID=” & id
    Dim sqlCmd As SqlCommand = New SqlCommand(Str, sqlCon)
    sqlCon.Open()
    sqlCmd.ExecuteNonQuery()
    sqlCon.Close()
    End Sub

    Private Sub PopulateGrid2()
    Dim dbCon As SqlConnection = New SqlConnection(strCon)
    dbCon.Open()
    Try
    Dim cmd As SqlCommand = New SqlCommand(“select ProductId,ProductName,ProductSize,OpeningStockLevel,ClosingStockLevel,convert(decimal(15,2),UnitPrice) as UnitPrice,QtyRejected,Units from ProductList order by ProductName”, dbCon)
    Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
    Dim dt As DataTable = New DataTable
    da.Fill(dt)
    GridView2.DataSource = dt
    GridView2.DataBind()
    Catch ex As Exception
    Throw ex
    Finally
    dbCon.Close()
    End Try
    End Sub

    Comment by Jasna | April 27, 2010 | Reply

  135. in my program, all the events GridView2_RowEditing,GridView2_RowCancellingEdit,GridView2_RowUpdating are fired twice.
    GridView2_RowUpdating is executing second time exception arises
    ArgumentOutOfRangeException was handled by user code. Specified argument was out of range of valid values, Parameter name: index

    Is this correct or is there anything wrong in my program
    Pls do help me to sort it out

    Comment by Jasna | April 27, 2010 | Reply

    • What is your .aspx?

      Comment by Some.Net(Guy) | April 27, 2010 | Reply

      • Comment by Jasna | April 28, 2010

  136. hello frnds i am trying update my total gridview by cliking on update button but am getting the error
    “Unable to cast object of type ‘System.Web.UI.LiteralControl’ to type ‘System.Web.UI.WebControls.TextBox’. ”

    updatebutton code
    —————-
    {

    SqlConnection con = new SqlConnection(“Data Source=DEVWR1\\DEVWR1SQL05;Initial Catalog=swetha;Integrated Security=True”);

    SqlDataAdapter da = new SqlDataAdapter(“update add_mdfy set name='” + ((TextBox)GridView2.Rows[e.RowIndex].Cells[4].Controls[0]).Text + “‘, occupation='” + ((TextBox)GridView2.Rows[e.RowIndex].Cells[5].Controls[0]).Text + “‘, phoneno=” + ((TextBox)GridView2.Rows[e.RowIndex].Cells[6].Controls[0]).Text + “,age=” + ((TextBox)GridView2.Rows[e.RowIndex].Cells[7].Controls[0]).Text + ” where property =” + ((TextBox)GridView2.Rows[e.RowIndex].Cells[1].Controls[0]).Text, con);

    DataSet ds = new DataSet();
    da.Fill(ds);
    GridView2.DataSource = ds;
    }

    source code
    ————

    <asp:TextBox ID="tb1" Visible='’ Text=” runat=”server”>

    <asp:TextBox ID="tb2" Visible='’ Text=” runat=”server”>

    <asp:TextBox ID="tb3" Visible='’ Text=” runat=”server”>

    <asp:TextBox ID="tb4" Visible='’ Text=” runat=”server”>

    Comment by swetha | May 4, 2010 | Reply

  137. source code
    ———-

    <asp:TextBox ID="tb1" Visible='’ Text=” runat=”server”>

    <asp:TextBox ID="tb2" Visible='’ Text=” runat=”server”>

    <asp:TextBox ID="tb3" Visible='’ Text=” runat=”server”>

    <asp:TextBox ID="tb4" Visible='’ Text=” runat=”server”>

    Comment by swetha | May 4, 2010 | Reply

  138. sorce code
    ———
    i used the itemtemplet for creating tha name,occupation,phoneno,age by spicifing the textbox names
    as tb,tb2,tb3,tb4 and property is boundfield and in dont have any primarykeys in this application.

    Comment by swetha | May 4, 2010 | Reply

  139. please provide the code in C# to update a row value by increasing 1 in a grid view on button click of that particulatr row

    Comment by harsh chhajer | May 18, 2010 | Reply

  140. i just to say that when using asp.net as a web builder the most stricking feature of asp.net is a session, cookies, databinding, and database handling and so on…………
    i meant to say is that when u insert the values in to the database whats is the purpose to handle these values into the database and in which way to handle the database values ok……… u r saying that by firing the query in to the database but i think thats not enough for the other learners just think that when using the concept the concept of databinding all the controls thats are related to the binding are fetch from the controls property but i says when u pooling the database into the other is not the proper way to handle and tell me sumthing abt the querystring i knw there are querybuilder, queryadapter, i knw but i says some feature of ado.net has not been mentioned here to describe the database properly. just try to understand wat i meant to say………………………
    another problem i have to learning during website is that all the learners is that asp.nert is a server scripting language…………and not at allllllllllllll…………..ok………….

    your student
    a.m. pettewar

    Comment by ashish | July 6, 2010 | Reply

  141. You saved me many more nights of stress tyring to update a gridview programatically. I was struggling with the

    “You can’t do something like GridView1(i)(j).Text = str or anything even close.” part of it. Trying every way under the sun to reliably get values from the gridview cells. I even tried e.newvalues. Didnt work so well. I would have never thought to cast them to another type! Thanks a million!!

    Comment by attrib | August 2, 2010 | Reply

  142. i’ve always found the easiest way to extract and update the data is to use templates… you can convert a read only cell into a textbox that way… from there, you can ctype the control using it’s id and reference it that way…

    you can then call a sqldatasource.update() command to update the database

    Comment by andrew | August 21, 2010 | Reply

  143. Thanks for your insightful topic.

    Comment by Chris Henning | February 12, 2012 | Reply


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.

%d bloggers like this: