Real World GridView: Bulk Editing


GridView is a tremendously useful control in ASP.NET 2.0.  Despite being much improved from the DataGrid of the ASP.NET 1.x era, GridView still lacks some features which always seem to be requested.  This is a multipart post on how to customize GridView to add some of this missing functionality.  I’ll post the full source code at the end of the series.  Hopefully this will be useful to everyone.


One of the most needed improvements is the ability to edit multiple rows at once.  By default, GridView allows users to modify only one row at a time, and requires the user to postback many times to switch between editable rows.  Here is a quick look at the “Out of the Box” GridView.



This is not the greatest user experience, so we’ll start by allowing the user to modify all of the rows before saving.  To begin, we will create a custom control which inherits from GridView.  This will allow us to override and change some of the behavior we don’t like.  One of the first things we want to change is how the rows get created.


   public class BulkEditGridView : System.Web.UI.WebControls.GridView
   {
      protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)
      {
         return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState | DataControlRowState.Edit);
      }
   }


What we have done here is make sure that every row which gets created has a rowstate of Edit, meaning it’s editable.  Since the row is now editable, the columns that are NOT read-only will show up as textboxes (for boundfields) or what ever their EditItemTemplate is.  Here is a look at our grid.



Wow! Looks great … are we done yet … um … not quite.  That would be great if that was all we had to do, but unfortunately there is a bit more.  Notice that there is no way to save our changes, which might be a <sarcasm>minor</sarcasm> problem for our user.  In ASP.NET 1.X, we might have just added a Save() function and made developers add code to the code-behind file to call our function.  Well, this is now a 2.0 world, and we are going to create a great design time experience.  We’ll allow developers to set the SaveButtonID on our grid, and we’ll take care of setting up all the event handlers.


   [IDReferenceProperty(typeof(Control))]
   public string SaveButtonID
   {
      get
      {
         string val = (string)this.ViewState[“SaveButtonID”];
         if (val == null)
         {
            return string.Empty;
         }
          return val;
      }
      set
      {
         this.ViewState[“SaveButtonID”] = value;
      }
   }


The IDReferenceProperty tells Visual Studio that this property contains the ID of another property on the page.  This way you get a nice dropdown of control ids in the Properties Window.  It’s just nice “fit and finish” that makes our control that much more developer friendly.


   protected override void OnLoad(EventArgs e)
   {
      base.OnLoad(e);


      //Attach an event handler to the save button.
      if (false == string.IsNullOrEmpty(this.SaveButtonID))
      {
         Control btn = RecursiveFindControl(this.NamingContainer, this.SaveButtonID);
         if (null != btn)
         {
            if (btn is Button)
            {
               ((Button)btn).Click += new EventHandler(SaveClicked);
            }
            else if (btn is LinkButton)
            {
               ((LinkButton)btn).Click += new EventHandler(SaveClicked);
            }
            else if (btn is ImageButton)
            {
               ((ImageButton)btn).Click += new ImageClickEventHandler(SaveClicked);
            }


            //add more button types here.
         }
      }
   }


   private void SaveClicked(object sender, EventArgs e)
   {
      this.Save();
      this.DataBind();
   }


The developer doesn’t have to write any C# to get the save button to save data!!  Thats a great developer experience, and the kind of standard we should hold ourselves to.  Of course, we want to be flexible and we will expose the Save() method publically so developers CAN access this programatically if they want.  We have added support for Buttons, LinkButtons, and ImageButtons, but there could be more controls you want to include.  The click event of all these controls is routed to the same SaveClicked handler which calls Save().  Pretty simple. 


On a Tangent: You might wonder what the RecursiveFindControl function is.  Why can’t we just use FindControl?  Well, FindControl() works great when we are not using MasterPages, but if our grid is in a different ContentSection than the Button, FindControl() won’t find the control we are looking for.  FindControl() is scoped to the NamingContainer that our control exists in.  To work around this, we recusively climb the tree of NamingContainers to find our button.


And now on to actually saving.  One thing we want to do, is make sure that we don’t save rows that have not changed.  Well, how do we know if a row changes?  We have to watch for it to change.


   protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
   {
      base.InitializeRow(row, fields);
      foreach (DataControlFieldCell cell in row.Cells)
      {
         if (cell.Controls.Count > 0)
         {
            AddChangedHandlers(cell.Controls);
         }
      }
   }


   private void AddChangedHandlers(ControlCollection controls)
   {
      foreach (Control ctrl in controls)
      {
         if (ctrl is TextBox)
         {
            ((TextBox)ctrl).TextChanged += new EventHandler(this.HandleRowChanged);
         }
         else if (ctrl is CheckBox)
         {
            ((CheckBox)ctrl).CheckedChanged += new EventHandler(this.HandleRowChanged);
         }
         else if (ctrl is DropDownList)
         {
            ((DropDownList)ctrl).SelectedIndexChanged += new EventHandler(this.HandleRowChanged);
         }
      }
   }


   void HandleRowChanged(object sender, EventArgs args)
   {
      GridViewRow row = ((Control) sender).NamingContainer as GridViewRow;
      if (null != row && !dirtyRows.Contains(row.RowIndex))
      {
         dirtyRows.Add(row.RowIndex);
      }
   }


   private List<int> dirtyRows = new List<int>();


Adding XxxxxChanged handlers to the controls allows us to know when a control in a row changed values.  If any value in the row changes, we mark the row as “dirty”.  Like with the buttons, I have added some of the most common input controls.  You may wish to add additional ones.  Additionally, TemplateFields might have nested controls, so you might want to recursively look for controls. 


I’m sure that you have already figured out what our save method will look like.  Just loop through the dirty rows and save them.


   public void Save()
   {
      foreach (int row in dirtyRows)
      {
         this.UpdateRow(row, false);
      }


      dirtyRows.Clear();
   }


Using the GridView’s UpdateRow() function allows our save to behave just like the “Out of the Box” save.  An associated DataSourceControl will be used to update the data, the RowUpdated event will fire, and everything else the basic save does.  Finally, here is the ASPX.


   <asp:Button runat=”server” ID=”SaveButton” Text=”Save Data” />
   <blog:BulkEditGridView runat=”server” id=”EditableGrid” DataSourceID=”AdventureWorks” AutoGenerateColumns=”False” DataKeyNames=”LocationID” SaveButtonID=”SaveButton” >
      <Columns>
         <asp:BoundField DataField=”LocationID” HeaderText=”LocationID” InsertVisible=”False” ReadOnly=”True” SortExpression=”LocationID” />
         <asp:BoundField DataField=”Name” HeaderText=”Name” SortExpression=”Name” />
         <asp:BoundField DataField=”Availability” HeaderText=”Availability” SortExpression=”Availability” />
         <asp:BoundField DataField=”CostRate” HeaderText=”CostRate” SortExpression=”CostRate” />
      </Columns>
   </blog:BulkEditGridView>


I wrote this to give you a basic understanding of how to create a bulk edit GridView.  Of course there are many enhancements you could add to this.  Perhaps you only want some of the rows to be editable, not all of them. Or, you want the grid to not be editable until the user clicks an “edit everything” button.  Maybe you would like all of the changes to complete in a transaction.  And probably you want this to do something I haven’t even thought of (I would like to know if you come up with something though).  I’ve added some of these enhancements for customers on projects, and most of them are not that difficult to implement.


 


NOTE: These comments are the authors own thoughts, and do not represent an official Microsoft recommendation.  This post is for educational purposes only.
   


UPDATE:  Thanks everyone for the feedback!!  Based on several of your comments, I have incorporated an inline insert into the grid (still very beta).  Also I have attached the source code as a zip for those people who can’t see the Got Dot Net workspace.  I can’t promise I’ll keep the attachment up to date, but the workspace will always have the latest.


UPDATE (JAN 2007): Updated source code is now available on CodePlex, and it should be easier to download than it was on GotDotNet.
http://www.codeplex.com/ASPNetRealWorldContr

RealWorldGrids.zip

Comments (241)

  1. Sunish Abraham says:

    Hi Matt,

    I am new to ASP.NET 2.0 GridView and the topic of this blog entry is something that I wanted to implement. Can you provide an example project/solution (here is my email address sunisha[at]comcast.net)? Thank you so much!

    Sunish

  2. SBrickey says:

    I’m curious how much effort it’d be to extend the gridview in such a way that multiple header/footers could be manipulated.

    I’ve got a gridview where the header is used for column names, and footer for column totals… similar to the bulk edit, I want to enable editing in each row, but just as importantly i’d like to dedicate a row for inserting (otherwise how many to a page? somewhat of an arbitrary number it seems).

    Right now my solution is to add a dummy record in the OnDataBind event… then in the OnDataBound, i handle index 0 as an exception.

    in terms of display, index 0 is also marked as the editable field, and in the column templates I’ve added the controls I need.

    This just seems like such a hack for my needs… and i’ve not even really pushed it (what if i wanted subtotal fields or something?)

    Thanks,

    -SBrickey

    me[at]sbrickey[dot]net

  3. mattdotson says:

    I’m going to cover this in a future post, but I’ve found one of the easiest/cleanest ways to do that is to modify the Table directly. GridView should have a single child control … the table, if you want to add one or more rows to that table, do it after databinding. I also use this approach for spanning cells.

  4. Trav says:

    Any chance of getting a vb version for lowly vb.net programmers?

  5. Khuzema says:

    any chance to get a source project. regards

  6. Michael says:

    Any easy way you’ve found/implemented to insert new rows inline on the GridView? I’d like to have a button next to "Edit" called "Insert" that would create a new row in the GridView, but wouldn’t actually create the row in the DB until they put in values and selected Create/Update. Thanks!

  7. Matt, great blog – and I really need this capability for my first 2.0 web app. But, I’m having trouble implementing it and wonder if I can get some help. First of all, I’m not sure where to put the various code pieces you identified. What goes into the custom server control class and what in the bulk gridview code behind? Also, where does the Viewstate for the SaveButtonID get created initially? I get error messages on that, as well as on the "public string SaveButtonID" method. Any help sure would be wonderful. Thanks.

  8. Let’s take a look at some real world uses for GridView.

  9. GridView is a great control, and out of the box it does a lot of wonderful stuff, but I haven’t worked on a project yet where it did everything I needed.  &quot;Real World GridView&quot; is an attempt to share some of the common customizations I end up

  10. mattdotson says:

    I posted the source code for this article @ http://www.gotdotnet.com/Workspaces/Workspace.aspx?id=1ecb6d2e-a104-48f7-a8fb-1622eba20852. Sorry for the delay & thanks for being patient.  Also, there is a part 2 of this article now.  I am working on part 3 which will include frozen headers.  Should be posted "soon" 🙂  Hopefully soon will be sooner than 3 months this time.

  11. mark r. reynolds says:

    Thanks for sharing your effort!

    I have been working with the BulkEditGridView today and have observed an issue regarding utlizing an ObjectDataSource associated with the BulkEditGridView control. The anomoly takes place when setting the BulkEditGridView ConflictDetection property to "CompareAllValues" instead of the default of "Overwritechanges". Upon executing an update the code dumps within the BulkEditGridView Save method during the first iteration of the updaterow loop with the following comment:

    "You have specified that your update method compares all values on ObjectDataSource ‘ObjectDataSource1’, but the dictionary passed in for oldValues is empty. Pass in a valid dictionary for update or change your mode to OverwriteChanges."

    The code works fine if you change the ConflictDetection property back. Additionally, I have only observed this anomoly in the case of ObjectDataSource association with the the BulkEditGridView. Have verified the anamoly by testing the code against a standard GridView. I will be happy to provide you with a project if you are interested in pursuing this issue.

    Again, thanks for your work. I’m sure the Real World GridView will be quite useful in the .Net community.

    mark r. reynolds…TBS  

  12. P says:

    Hi matt,

    I am finding difficult to locate "GridView" code in this location  http://www.gotdotnet.com/Workspaces/Workspace.aspx?id=1ecb6d2e-a104-48f7-a8fb-1622eba20852

    can you help me on this…

    Regards,

    P

  13. mattdotson says:

    P, it’s under the source control section of the workspace. $/RealWorld.Grids/BulkEditGridView.cs

  14. mattdotson says:

    Thanks Mark.  I think I understand your issue, and will investigate it.  If I find a solution, I will post it here.

  15. mattdotson says:

    By the way, Part 3 is done.  Check it out here: http://blogs.msdn.com/mattdotson/archive/2006/03/02/542613.aspx

  16. James says:

    This looks like what I need to use. I found the BulkEditGridView.cs and added it to my app_code folder. I am having troubles referencing this from the aspx file. I see the example above, but being new to the .net world I’m still a bit confused.

    I dropped a regular gridview on the page and connected to the datasource and that worked fine. Then I changed the <asp:GridView tag to <asp:BulkEditGridView

    but this gives an error [not a known element].

    Any help getting this working would be greatly appreciated.

    Thanks!

  17. James says:

    I guess I see that the tag prefix is the problem. Instead of using <asp:

    I need to use something else. Above example shows <blog:

    but in another example I see <rwg:

    This is the part I need to know how to tie together.

    Is there something else that needs to be installed or can this be used by just including the BulkEditGridView.cs file in the the App_Code folder?

    Thanks.

  18. sirisha says:

    Hi Matt,

      For the bulk edit data grid view, is there a way that the user selectes the rows that he wants to edit and when he clicks edit then all the common columns will become editable. Then when the user enters value in one column all the other columns will be updated with this value.

     ThankYou

     

  19. cc says:

    It seems that the FrozenGridView produces an error if the query which poplulates the grid returns no results.

    Object reference not set to an instance of an object:

    foreach (DataControlFieldHeaderCell th in this.HeaderRow.Cells)

  20. Matt says:

    James, I would keep any custom controls you write as a seperate dll.  I’ve used <blog: and <rwg: in different places, and these are defined at the top of the aspx pages.  

    Sirisha, you could definately extend the grid to create the functionality you want.

    CC, thanks for the info, I’ll include this fix the next time I post some code.

    –Matt

  21. brian says:

    Here is VB version I translated from Matt’s C#.

    mports Microsoft.VisualBasic

    Imports System.Web

    Imports System.Web.UI

    Imports System.Web.UI.WebControls

    Imports System.ComponentModel

    Imports System.Security.Permissions

    Namespace nwss.controls

       <AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal), _

                AspNetHostingPermission(SecurityAction.InheritanceDemand, level:=AspNetHostingPermissionLevel.Minimal), _

                ToolboxData("<{0}:BulkEditGridview runat=""server""> </{0}:BulkEditGridview>")> _

       Public Class bulk_edit_gv

           Inherits GridView

           Protected Overrides Function CreateRow(ByVal rowIndex As Integer, ByVal dataSourceIndex As Integer, ByVal rowType As System.Web.UI.WebControls.DataControlRowType, ByVal rowState As System.Web.UI.WebControls.DataControlRowState) As System.Web.UI.WebControls.GridViewRow

               Return MyBase.CreateRow(rowIndex, dataSourceIndex, rowType, DataControlRowState.Edit)

           End Function

           <IDReferenceProperty(GetType(Control))> _

           Public Property saveButtonID() As String

               Get

                   Dim val As String = Me.ViewState("saveButtonID")

                   If val = Nothing Then

                       Return ""

                   Else

                       Return val

                   End If

               End Get

               Set(ByVal value As String)

                   Me.ViewState("saveButtonID") = value

               End Set

           End Property

           Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)

               MyBase.OnLoad(e)

               If Me.saveButtonID.ToString > "" Then

                   Dim btn As Control = RecursiveFindControl(Me.NamingContainer, Me.saveButtonID)

                   If btn IsNot Nothing Then

                       If TypeOf (btn) Is Button Then

                           AddHandler CType(btn, Button).Click, AddressOf saveclicked

                       ElseIf TypeOf (btn) Is LinkButton Then

                           AddHandler CType(btn, LinkButton).Click, AddressOf saveclicked

                       ElseIf TypeOf (btn) Is ImageButton Then

                           ‘AddHandler CType(btn, ImageButton).Click, AddressOf saveclicked

                       End If

                   End If

               End If

           End Sub

           Protected Overrides Sub InitializeRow(ByVal row As System.Web.UI.WebControls.GridViewRow, ByVal fields() As System.Web.UI.WebControls.DataControlField)

               MyBase.InitializeRow(row, fields)

               For Each cell As DataControlFieldCell In row.Cells

                   If cell.Controls.Count > 0 Then

                       addChangeHandler(cell.Controls)

                   End If

               Next

           End Sub

           Private Sub addChangeHandler(ByVal controls As ControlCollection)

               For Each ctrl As Control In controls

                   If TypeOf (ctrl) Is TextBox Then

                       AddHandler CType(ctrl, TextBox).TextChanged, AddressOf handleRowChanged

                   ElseIf TypeOf (ctrl) Is DropDownList Then

                       AddHandler CType(ctrl, DropDownList).SelectedIndexChanged, AddressOf handleRowChanged

                   ElseIf TypeOf (ctrl) Is CheckBox Then

                       AddHandler CType(ctrl, CheckBox).CheckedChanged, AddressOf handleRowChanged

                   End If

               Next

           End Sub

           Sub handleRowChanged(ByVal sender As Object, ByVal args As EventArgs)

               Dim row As GridViewRow = CType(sender, Control).NamingContainer

               If row IsNot Nothing And Not dirtyRows.Contains(row.RowIndex) Then

                   dirtyRows.Add(row.RowIndex)

               End If

           End Sub

           Private dirtyRows As New System.Collections.Generic.List(Of Integer)

           Private Function RecursiveFindControl(ByVal root As Control, ByVal id As String) As Control

               If root.ID = id Then

                   Return root

               End If

               For Each c As Control In root.Controls

                   Dim t As Control = RecursiveFindControl(c, id)

                   If t IsNot Nothing Then

                       Return t

                   End If

               Next

               Return Nothing

           End Function

           Public Sub save()

               For Each row As Integer In dirtyRows

                   Me.UpdateRow(row, False)

               Next

               dirtyRows.Clear()

           End Sub

           Private Sub saveclicked(ByVal sender As Object, ByVal e As EventArgs)

               Me.save()

               Me.DataBind()

           End Sub

       End Class

    End Namespace

  22. Cliff says:

    Thanks for the VB version. I am struggling to get this working however. I am a relatively new convert to ASP.Net from Classic ASP and am still having problems with some of the basic concepts. Can someone give me an "idiots guide" to taking this code and using it in a simple aspx page?

    Thanks,

    Cliff

  23. Brian says:

    Cut and paste it out of here into a new custom

    vb file in the appcode folder of your website.

    Change the namespace to something meaningful for you.

    For more information read the walkthrough "Developing and Using a custom server control" in the on-line help library installed with web dev. If you didn’t install it, you should. This will tell you how to create,deploy, and use custom controls.

  24. Cliff says:

    Thanks Brian, that really helped and I have it working now. This is a great custom control.

    Your help and rapid response are really appreciated.

    Cliff

  25. Cliff says:

    I have another ‘real world’ variant that looks an ideal candidate for BulkEditGridView and would, I am sure, be useful to many developers. In content management systems I am frequently having to provide administrators with the ability to set the sort order for a group of records (departments, categories, latest products, etc) so they are displayed to customers in a specified order. The BulkEditGridView provides a great basis for this by setting the only editable column to be the sort order. However, I need to be able to validate that the sort order is an integer value between 1 and the total number of rows, with no repeats. I have some classic ASP I use to do this but it would save me hours of work each time if this could be integrated with BulkEditGridView.

    So, my question is, how could BulkEditGridView be modified to achieve this validation? Alternatively, would the validation be better performed outside of the control and if so, how?

    Many thanks,

    Cliff

  26. Eric D. says:

    I have a unrelated question about Server Controls someone might know the answer to. I made a Server Control that has a SQL Connection string as a property. How do I make the property bindable like the SQLDataSource property so a user can just select a Connection String from the web.config? The SQLDataSource ConnectionString property is just a string- how does it tell the designer to bind it as a SQL Connection String?

  27. Scott C says:

    How hard would it be to implement templated Columns so that you could have validators and such?

  28. John M says:

    This would be really cool if someone published a downloadable Server Control out of this (don’t think that can be done with my ASP.Net Express version – I may be mistaken).

  29. Scott says:

    I implemented much the same design to solve one of my UIs and it worked out well. I just built out a Custom Web Controls assembly for my custom grid view, registered it on the page and presto, fully editable gridview. The issue I ran into was with my gridview skins…if you’re not familiar with them, they are basically css styles for your gridview that you drop in the App_Themes folder of your webapp. For some reason my custom grid view will not respect the skin I assign to it…I’m guessing its a pathing issue perhaps? Have you ever come accross this issue or have an idea of how to fix it?

  30. Christian Lebon says:

    This is very cool.  What would really take this to the next level is if you added the code to insert new rows

  31. Bill says:

    I was looking over this and would like to try and implement it but am having some difficulty.  I am new to .NET and like James question above, I am wondering how to get my program to recognize rwg tags and BulkEditGridView as an object.  I added the following to my web.config file:

    <pages>

         <controls>

           <add assembly="RealWorld.Grids" namespace="RealWorld.Grids" tagPrefix="rwg"/>

         </controls>

    </pages>  

    But it cannot find the assembly RealWorld.Grids, of course because I don’t have a file in my website called that.  But the file is not in the source code section of Matts gotdotnet blog, and I don’t know how to create that file, if I have to use some of the other files given to crete a dll or what.  If someone wonders through here that could shed some light onthis for me I would definately appreciate it.    I apologize if I didn’t provide enough info on my problem.

    -Bill

  32. CC says:

    Bill,

    You are close. You need to download the BulkEditGridView.cs file from Matt’s workspace and place it in your App_Code folder.

    The web.config file only needs to have:

    <pages>

    <controls>

    <add namespace="RealWorld.Grids"  tagPrefix="rwg"/>

    </controls>

    </pages>

    Then in your aspx page, you can drop in a regular gridview control and change the tag to <rwg:BulkEditGridView and things should be fine.

    Hope this helps.

  33. CliffMitchell says:

    Matt,

    I notice that when I set the EmptyDataText attribute on a BulkEditGridView control I get an error when the data set is empty:

    Unable to cast object of type ‘System.Web.UI.WebControls.TableCell’ to type ‘System.Web.UI.WebControls.DataControlFieldCell’.

    Any suggestions as to how to get around this?

    Thanks,

    Cliff

  34. Thiru says:

    I am having difficulties in finding the source code for this gridview control. Please help.

    Thanks,

    Thiru

  35. Dan says:

    I am also trying to find the source code for this. Please excuse me as I am a newbie to the ASP.net world.

  36. Matt Dotson says:

    I have updated the BulkEditGridView to fix the EmptyDataText problem.  Thanks Cliff!!

  37. Matt Dotson says:

    I have checked in changes to allow inline inserts to the BulkEditGridView.  It’s still beta and I haven’t done a whole lot of testing on it.  Try it out and let me know what you think.  

    Eventually I’ll get around to writing an article on it.

    PS. You have to set EnableInsert=true and there should be a blank row at the bottom.  You have to click the save button to perform the insert on the server.

  38. Dan C says:

    I have posted a VB version on the gotdotnet workspace. Can somone help with the testing

  39. Diego says:

    Great controls!!!!

    Is there a release in C#?

  40. Christian Lebon says:

    I am testing this as we speak.  Two things if you guys done mind.

    What is the syntax on using the DropDownField control?  I am hoping that is like a combobox that lets you either chose or type free text.

    And what about throwing a date picker in there?  That would be sweet as well.  

    So you know, I have throw this into an Atlas update panel and it works well.  Thanks so much!

    Christian

  41. Steve says:

    Happy to test – tell me how to find it!

  42. Christian Lebon says:

    I notice when there are no records returned I am not seeing the insert row.  how can enable this regardless of whether there are records returned or not.

  43. mattdotson says:

    Steve … there is a link to the zip file at the end of the article.

    Diego … all of my code is in C#, you can download the zip, or see the current code in the GotDotNet workspace.

    Christian … the DropDownField is for a dropdown column in the grid view.  It has a few issues though that i haven’t had time to work out yet.

    That’s awesome to hear it works with atlas, I hadn’t tried that yet.

    I’m going to look into the no rows issue.

  44. Diego says:

    > Diego … all of my code is in C#, you can download the zip, or see the current code in the GotDotNet workspace.

    Uhm… I downloaded the files, one a time, from source control  (I can only use html interface 😐 ), but I can’t find the zip.

    However there is no problem, all works fine 😉

    Thank you and bye.

    Diego

  45. Christian says:

    Matt,

    Great.  Please let me know if you get that combobox worked out and the syntax if you would.

    One of the things that I am trying to figure out is how to put Atlas Autocomplete extender textboxes in a grid.  That way, you get the combo type setup, but it loads nothing until used.  I think that would be a simply awesome tool.

  46. Joe says:

    Set everything up using an Access DataSource and an Update command in the datasource, but when I click Save button, the changed data in the Gridivew goes back to the original data and I don’t get any error. The code is making it to the "Me.UpdateRow(row, False)", but no updating is taking place. The Update SQL statement in my DB is

    UPDATE T2_Wo SET [Project#] = @Project, [Task Description] = @Description where ID=@ID

    <UpdateParameters>

               <asp:parameter Name="Project"/>

               <asp:parameter Name="Description"/>

               <asp:Parameter Name="ID"/>

               </UpdateParameters>

    Any ideas?

    Joe

  47. Elizabeth says:

    Life saving topic.  I worked with VS2003 DataGrids now I have to work in VS2005 GridView, bulk editing plus multi-view.  I will look at the VB code that is attached and try to decipher.  

  48. mattdotson says:

    Good news … I’ve made some more updates.  And I’ve posted a zip on the Releases of the GDN Workspace for everyone who is having trouble with the source code control.

  49. molhokwai says:

    Hi Matt,

    I’ve tested implementing the BulkEdit RealWordl GridView. Works fine with a SqlDataSource with UpdateCommand and all… But the only way I could get it to work (with a DataSet) is to do the following:

    – Implement the RowUpdating method (in the code-behind page) and in the method get the bound row from the DataSource and update the values

    – And afterwords call the DataSet’s corresponding table adapter’s Update method…

    Is there a way to just bind the RealWorld Grid View an let it do all the work without having to code the update and all?

    Thanks…

  50. Lars says:

    This is just what I need for my project! But I want only to enabled only some rows for editing, while the others are read only.

    I have tried quite a few approaches, but no success. In some event handlers, row.DataItem == null, and in RowDataBound it seems to be too late to change rowState, but row.DataItem != null.

    I use a ObjectDataSource, which seems to complicate matters even more…

    What am I missing?

  51. Amino says:

    I must thank mattdotson for his great job. I have integrated it into my project. I am able to get both objectdatasource and sqlDataSource working without any problems.

    So great, so simple.

    weldone

  52. ShaunR says:

    Great blog, and controls..thanks!

  53. 先日ObjectDataSource,ObjectDataSourceViewを…

  54. Phil says:

    I have the bulk Edit displaying data but when I call the save I get this error:

    "You have specified that your update command compares all values on SqlDataSource ‘AccessDataSource2’, but the dictionary passed in for oldValues is empty.  Pass in a valid dictionary for update or change your mode to OverwriteChanges."

    Any help would be great.

  55. rosy says:

    its very helpfull to us thankx

  56. Srinivasa Raghavan says:

    how to do bulk update of rows using  sqldatasource control.

  57. WadeC says:

    Got any tips on how you could best implement the EditRow property…

    I have a grid with a template field containing a user control. When the user control is pressed I need to know the row it is on. I am having difficulty obtaining this information with your grid. Previously I used the EditRow.

    I have been trying to add an OnRowClick event to store the row in a hidden field – but I am finding that the user control’s event can fire before the rowclick and there is no row info available.

    WadeC

  58. ndramkumar says:

    I had used the Gridview and it is very useful for my requirement. But I have some issues with it. Please anybody help me to solve it out.

    My requirement is to dynamically generate columns (Bound and Template Columns as required) in GridView control. So I need to dynamically bind the controls at runtime. I need to do a bulk update to the database from the GridView.

    I am facing problems in binding the control dynamically. When I dynamically create a text box and bind it to a GridView, during the update the value of the textbox is not properly passed to the ControlParamter of SqlDataSource control which will update the database. The values updated to the database are null.

    Initially I used the Page_Load method to generate the controls in GridView and later changed it to Page_Init in order to handle the post back issues with the dynamically created textbox.

    What is the problem that I am facing?

    Please suggest a solution for this problem.

    I am attaching the source code which dynamically binds the controls to the GridView at runtime.

    void ITemplate.InstantiateIn(System.Web.UI.Control container)

       {

           switch (_templateType)

           {

               case ListItemType.Header:

                   //Creates a new label control and add it to the container.

                   Label lbl = new Label();            //Allocates the new label object.

                   lbl.Text = _columnName;             //Assigns the name of the column in the lable.

                   container.Controls.Add(lbl);        //Adds the newly created label control to the container.

                   break;

               case ListItemType.Item:

                   //Creates a new text box control and add it to the container.

                   TextBox tb1 = new TextBox();                            //Allocates the new text box object.

                   tb1.DataBinding +=  new EventHandler(tb1_DataBinding);   //Attaches the data binding event.

                   tb1.ID = _columnName;

                   tb1.Columns = 15;                                      //Creates a column with size 4.

                   //tb1.Text = _dr[_columnName].ToString();

                   container.Controls.Add(tb1);            //Adds the newly created textbox to the container.

                   break;

               

               case ListItemType.AlternatingItem  :

                   //Creates a new label box control and add it to the container.

                   Label lb1 = new Label();                            //Allocates the new label object.

                   container.Controls.Add(lb1);                            //Adds the newly created label to the container.

                   break;

               case ListItemType.EditItem:

                   TextBox tb2 = new TextBox();                            //Allocates the new text box object.

                   tb2.DataBinding += new EventHandler(tb1_DataBinding);   //Attaches the data binding event.

                   tb2.ID = _columnName;

                   tb2.Columns = 15;                                      //Creates a column with size 4.

                   tb2.ReadOnly = false;

                   container.Controls.Add(tb2);                            //Adds the newly created textbox to the container.                

                   break;

               case ListItemType.Footer:

                   CheckBox chkColumn = new CheckBox();

                   chkColumn.ID = "Chk" + _columnName;

                   container.Controls.Add(chkColumn);

                   break;

           }

       }

       /// <summary>

       /// This is the event, which will be raised when the binding happens.

       /// </summary>

       /// <param name="sender"></param>

       /// <param name="e"></param>

       void tb1_DataBinding(object sender, EventArgs e)

       {

           TextBox txtdata = (TextBox)sender;

           GridViewRow container = (GridViewRow)txtdata.NamingContainer;

           object dataValue = DataBinder.Eval(container.DataItem, _columnName);

          if (dataValue != DBNull.Value)

           {

               txtdata.Text = dataValue.ToString();

           }

     

       }

  59. Jurjen de Groot says:

    I’ve been using the control. GREAT, however I can’t seem to get the Pager to be anywhere but to the Left of the control. Setting the PagerStyle HorizontalAlign to "Center" (or any other value) doesn’t make a difference. It won’t move !!

    Anybody else experience the same and maybe got a solution to this ?

    Regards,

    Jurjen de Groot

    Netherlands.

    info AT gits DASH online DOT nl

  60. Roy DA says:

    In reference to the comment below…How is what molhokwai proposes actually accomplished? I can use the Real World Gridview great if it’s a one-for-one update, meaning for every grid record, there exists one database record.

    However, when I try to use the bulk edit on a summary-style page in which one grid record may have several associated database records, it just doesn’t work… No error, it just refreshes with nothing occurring. HELP!

    # re: Real World GridView: Bulk Editing

    Tuesday, May 30, 2006 4:24 AM by molhokwai

    Hi Matt,

    I’ve tested implementing the BulkEdit RealWordl GridView. Works fine with a SqlDataSource with UpdateCommand and all… But the only way I could get it to work (with a DataSet) is to do the following:

    – Implement the RowUpdating method (in the code-behind page) and in the method get the bound row from the DataSource and update the values

    – And afterwords call the DataSet’s corresponding table adapter’s Update method…

    Is there a way to just bind the RealWorld Grid View an let it do all the work without having to code the update and all?

    Thanks…

  61. k.ekezie says:

    the BulkEditgridview works nicely. But I have one issue/question. Is it possible to make the grid generic for any table. By that I mean, do I have to write SQL code (i.e for inserts/updates/deletes for each table in the data source?

  62. Jay says:

    Hi Matt

    Nice article. I have a question, how exactly we can handle if there are DBcombo’s involved in this application in other words how do we validate the value of the 2nd combo based on the first combo selection before saving it the database.

    Thanks

    Jay

  63. Adam says:

    Hey, thanks for the BulkEditGridView! Now, is there an easy way to turn off validation for the insert row? i.e. so it can be left empty? Thanks!!!

  64. Ram says:

    Hi There

    Can someone tell me where exactly is it storing the record values in the class. In other words i need to do some validation on particular colmns.

    Thanks

    Ram

  65. Fearson says:

    your article is very usefull to me,thanks a lot

  66. Ulysses says:

    is it possible that each row is put into the magicajax panel. my purpose of doing it is that, i wanted the row to be update but without reloading the whole gridview..

  67. Miguel says:

    Have you thought of implementing a "undo" command? I implemented your excellent solution adding support to RadioButtonList, but I wanted to make it possible to revert the changes in a single click. One Idea would be simply make DirtyRows.Clear() and Save(), but unfortunately, although it does not update anything, the selected radiobuttons are still the changed ones.

  68. Dave says:

    I copied the BulkEditGridView.vb to my appdata directory and added the line <%@ Register Namespace="RealWorld.Grids" tagPrefix="rwg" %> to the top of my aspx page.  This line is underlined in green and a message stating that "the namespace does not have any public methods" appears.  What am i missing?

  69. Jeff says:

    I had the same problem as Mark above when trying to use optimistic concurrency with this grid.  What I found out was that the base GridView class only keeps track of old values for the row with the EditIndex.  I attached some code below to store the old values in the viewstate, and then add them to the colleciton during an update.  It needs some work in order to accomodate different type of data keys, but this should help get someone started.

           // DataTable to store original values

           private DataTable originalDataTable;

           private bool tableCopied = false;

           protected override void OnRowUpdating(GridViewUpdateEventArgs e)

           {

               string select = "";

               // Retrieve original values data table from view state

               if (originalDataTable == null)

                   originalDataTable = (DataTable)ViewState["originalValuesDataTable"];

               // Consturct a select string to retrieve original row based on key values

               foreach (string key in e.Keys.Keys)

               {

                   if (select.Length > 0)

                       select += " and ";

                   Type type = e.Keys[key].GetType();

                   if (type == typeof(string))

                       select += String.Format("{0} = ‘{1}’", key, e.Keys[key]);

                   else if (type == typeof(DateTime))

                       select += String.Format("{0} = ‘{1:g}’", key, e.Keys[key]);

                   else

                       select += String.Format("{0} = {1}", key, e.Keys[key]);

               }

               // Find original row

               DataRow[] rows = originalDataTable.Select(select);

               if (rows.Length == 0)

                   throw new InvalidOperationException("Could not locate original values for row being updatated");

               DataRow row = rows[0];

               // Add original values to OldValues collection

               foreach (string key in e.NewValues.Keys)

               {

                   if (row[key] == System.DBNull.Value)

                       e.OldValues.Add(key, null);

                   else

                       e.OldValues.Add(key, row[key]);

               }

               base.OnRowUpdating(e);

           }

           protected override void OnRowDataBound(GridViewRowEventArgs e)

           {

               // Save data table of original values to view state

               if (e.Row.RowType == DataControlRowType.DataRow)

                   if (!tableCopied)

                   {

                       originalDataTable = ((DataRowView)e.Row.DataItem).Row.Table.Copy();

                       ViewState["originalValuesDataTable"] = originalDataTable;

                       tableCopied = true;

                   }

               base.OnRowDataBound(e);

           }

  70. Dave says:

    I have never used a custom control and am new to ASP development.  Do I need to compile the .vb file before I can use it in my website?  I have gridviews in my site, but would like to use the mutli row editing.  

    I would be most thankful if anyone could provide steps start to finish on how to make the switch. I’ve tried several things but cannot get it right. I’ve searched endlessly on web and have not been able to figure it out.

  71. Jeffry says:

    May I have a sample project as well? (jevans161 @ yahoo.com).

    Thanks,

    Jeffry

  72. Miguel says:

    I have an EditTemplate in the BulkEditingGridView and a CheckBox. The event for CheckedChanged is changing the TextBox that is databound. Unfortunately, although the Checkbox has AutoPostBack=true and the TextBox changes to what I want, the DirtyRows is not updated, so if I don’t make any other change Save() does not work…

    All this is inside an UpdatePanel, do you have any idea why this behaviour happens?

  73. Validation is actually pretty easy for this control, although it does need to be manually handled during the Save event. First, don’t set the SaveButtonID property so you can handle the event yourself. I handle the Click event of my save button, and I’ve attached my code below. The BulkEditGridView control I’m working with has four columns, and only the fourth column is enabled for editing. The user enters decimal values, and anything else needs to be rejected. My code detects validation failures, sets an error Label control, and highlights the cell with the problem. My control is called Editor. Hopefully you can put this to work in your own project!

    <pre>protected void Save_Click(object sender, EventArgs e)

    {

     foreach (GridViewRow r in Editor.DirtyRows)

     {

      TextBox c = (TextBox)((DataControlFieldCell)r.Controls[3]).Controls[0];

      try

      {

       decimal d = decimal.Parse(c.Text);

      }

      catch

      {

       r.Cells[3].BackColor = System.Drawing.Color.Pink;

       c.BackColor = System.Drawing.Color.Pink;

       lblError.Text = "<br /><br />You entered an invalid number in the editor. Please correct and click Save again.";

       return;

      }

      r.Cells[3].BackColor = System.Drawing.Color.Empty;

      c.BackColor = System.Drawing.Color.Empty;

     }

     lblError.Text = "";

     Editor.Save();

     // …

    }</pre>

  74. Seetapati says:

    First of all, this is a great control. However, I have a couple of questions… How do you implement his control with an objectdatasource where the update method has no arguments. The update method in the object calls a stored procedure that takes 2 parameters that come from a session variable. Any ideas?

  75. Shahzad Godil says:

    Great control.  Save my week of time.  I was able to implement it using ObjectDataSource without any change.  It simply work by just binding to my object datasource and Insert/update/select work as normal gridview.

    In case of any issue if somebody is facing, he can chat me on my msn messenger : shazadgodil@hotmail.com or

    EMail : shahzadgodil@gmail.com

  76. Shahzad Godil says:

    Only issue I am facing is that my custom skin is not applying to this grid.

  77. Tomer says:

    How would i prevent from all text boxes to appear editable?,meanning i would like to

    make the row editable only after user select the row.

    EMail : tomerdr@hotmail.com

  78. Binod says:

    Thanks to all of you.. I have been waiting for the same and have tried to do the same thing.. but could not achieved.

  79. LSUgirl says:

    Great tool.  I do have a question.  I have a sql that contains an outer join.  So, every time, I’m bringing back 2 rows from the database.  That could mean 2 inserts, one insert/one update or 2 updates.  I currently have all the rowstate set to Edit but the Insert isn’t working on the Save Row.

    Can I change the rowstate dynamically after the grid is dataloaded?  I need to check an id column in the grid view (hidden label) to find if it’s an update or insert.

  80. simon says:

    It is a very great tool to use. But I got a problem…. My gridview is binded to an objectDataSource, dont know why updateRow methods can not set the editable field values to the objectDataSource, which results in that all the editable fields appears null in the object of the objectDataSource… do you have any idea???

    Thank you

  81. Harry says:

    You need to call the Save() method, otherwise the DataSource is not updated.

  82. Jesper says:

    If there is no data bound to the table then there is an error in the method CreateInsertRow()

    Object reference not set to an instance of an object.

    this.InnerTable is null

    What should be done to fix this?

    Regards Jesper

  83. Judah says:

    I think I have the same problem as simon from 10/24.  When updating, any column that I have set visible="false" gets sent to the datasource with a value of NULL.  Any way to make it forward the original value?

    Thanks

    Judah

  84. Jesper says:

    Hi!

    When there is no data from the source, when using bulkedit-insert, only one new insert row is put into the gridview. But no headers are shown! (which is, beacause there is no data)

    Is there a way to bind headers to the only insert row anyway?

    I would like to use it in such a way that , when I enter this page with the gridview (with two columns) the first time I’ll have no data in the database so there should only be an empty insertrow. Above the insertrow I would like a headerrow with with headers describing the columns.

    When I have data in the database it should be a number of rows with data and an empty insert row in the bottom.

    Does any one have any ideas?

    /Jesper

  85. Evgueni says:

    Hello,

    I downloaded your solution (it’s excellent, by the way), but one thing doesn’t work — the IDReferencePropertyAttribute on SaveButtonID does not cause my Visual Studio to display a drop-down of buttons on the page — the property appears just like a text box. Do you know why this might be? Thanks.

    Evgueni

  86. Ron Delzer says:

    You can simplify the code in your OnLoad override by casting to the IButtonControl interface rather than the specific button class. This version supports Button, LinkButton, and ImageButton and any other class that implements IButtonControl.

           protected override void OnLoad(EventArgs e)

           {

               base.OnLoad(e);

               if (!String.IsNullOrEmpty(this.SaveButtonID))

               {

                   IButtonControl button = (IButtonControl)RecursiveFindControl(this.NamingContainer, this.SaveButtonID);

                   button.Click += new EventHandler(SaveClicked);

               }

           }

  87. Jit says:

    Nice work , but there are two things I still want to ask. Firstly how do I use a DropDownList (Probably as a template column) and a readonly field value, which will be changed on selection of dropdown value. And I want to save both (DropDownList value and readonly field value as bulk).

  88. Vincent D'Souza says:

    I love this extension of the GridView.  But need some more help.  I need to make sure the total of the numeric colums allways match 100.  Could you let me know how can it be done, please?  Also, is there anyway this validation can be done on the client side?

    Greatly appreciate if you could email me the answer at vincent.dsouza@bellsouth.com

    Thanks,

    Vincent

  89. Sarasu says:

    Need Help!!!

    I am using Dataset to fill my Gridview so i had not provided any DataSource as my dataset gets data through webserivce. When i click the save button its not really saving anything. I am doing something wrong ?

    My aspx page code for gridcontrol

    <asp:Button runat="server" ID="SaveButton" Text="Save Data" />

     <rwg:BulkEditGridView ID="GridView2"  AutoGenerateColumns="False"    DataKeyNames="Release Date" SaveButtonID="SaveButton" runat="server" OnRowDataBound="GridView2_RowDataBound" OnRowUpdating="GridView2_RowUpdating">

                   <Columns>

                   <asp:TemplateField HeaderText="ID">

    <ItemTemplate>

    <asp:HyperLink NavigateUrl=<%# "company.aspx?ID=" + Eval("ID")%>  Target="_self" ID="HyperLink" runat="server">

           <asp:Label ID="erd2" Text=<%# Eval(" ID")%> runat="server"> </asp:Label>

            </asp:HyperLink>

    </ItemTemplate>

    </asp:TemplateField>

           <asp:TemplateField HeaderText="ReleaseDate">

           <ItemTemplate>

    <asp:Textbox ID="erd" Text=<%# Eval("Release Date")%> runat="server"> </asp:Textbox>

          </ItemTemplate>

               <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />

           </asp:TemplateField>

           <asp:BoundField DataField="Comp IDs" HeaderText="CompIds">

               <ItemStyle HorizontalAlign="Center" />

           </asp:BoundField>    

           <asp:BoundField DataField="Count" HeaderText="Count">

               <ItemStyle HorizontalAlign="Center" />

           </asp:BoundField>

           <asp:BoundField DataField="Date Imported" HeaderText="DateImported">

               <ItemStyle HorizontalAlign="Center" />

           </asp:BoundField>

                   </Columns>

               </rwg:BulkEditGridView>

    my codebehind coded

     DataSet DetailsDS = GetDetails.GetDetails(InputXML);

           GridView2.DataSource = DetailsDS;

           GridView2.DataBind();

  90. Boerge says:

    Hi, I’m having trouble inserting the new rows.

    I’ve got checkboxes in the gridview which I have to change the values from true/false to ‘Y’ or ‘N’.

    THis is what I’m trying to do:

    protected void BulkEditGridViewPipelineContractors_RowInserting(object sender, RealWorld.Grids.GridViewInsertEventArgs args)

       {

           RealWorld.Grids.BulkEditGridView grid = ((RealWorld.Grids.BulkEditGridView)sender);

    //This is where it fails. index out of bounds..

           GridViewRow row = (GridViewRow)((RealWorld.Grids.BulkEditGridView)sender).Rows[args.RowIndex];

    //Then I’m changing the data like this

    //(this works when updating rows, and also when inserting rows in detailsview)

    CheckBox chk = ((CheckBox)row.FindControl("CheckBoxFabricationContractor"));

           args.NewValues["COLUMN_NAME"] = Helper.BoolToString(chk.Checked);

    }

  91. Vivek says:

    Need Help !!!

    I have enabled paging in my GridView, this creates a problem.. i am not getting a proper solution, kindly help me out.

    My problem is..

    I have a Bulk Edit Grid and it contains 4 field in which only one is editable(CheckBox is used to edit this field).

    Now suppose user makes some changes and do not save it, but goes to another page of GridView and also make some changes there(On other page of GridView) but when he comes back to the intial page which he was editing before, the page lost all its edited value because it is binded again to database. Can this edited value somehow be restored when user change the page of gridview.

    Thanks

    Vivek

  92. amit says:

    in some applications there is a provision that if u type a word by selecting a column,u r navigted to the matching entry in that column.can this functionality be implemented in this gridview

  93. Javier Cabrera says:

    How you can decide which column you can put in Edit mode, I see you can do that because in the aspx example you are working with bounded columns, but I am filling the grid at run time, using a DataTable.

    I appreciate if u can help me and sorry for my english, but i am Peruvian.

  94. Christophe Vigouroux says:

    Hi,

    I have modified the BulkEditGridView in order to be able to choose the position of the insert row at the bottom (just above the pager line and the footer) or at the top (just under the header).

    This works nearly fine, but when I use it at the top, a TargetInvocationException occurs when I click save, on the save.DataBind() statement (in method SaveClicked).

    I have another strange behavior, which must be tied. I also had a property to the grid in order to choose or not to make it editable. When I choose to not, then I just have my insert row at the top and my list not editable. Paging works fine, insertion also. But I added a "select" command to the lines, and when I click on it, an empty line appears just under my inserting row, making the paging rows disappear…

    Any clue about this experience ? Has somebody tried to put the insert row at the top ?

    Here is an exerpt of the code I use :

    protected virtual void CreateInsertRow()

           {

               int rowIndex = 0;

               if (this.InsertRowPosition == RowPosition.Bottom)

               {

                   rowIndex = this.Rows.Count;

               }

               GridViewRow row = this.CreateRow(rowIndex, -1, DataControlRowType.DataRow, DataControlRowState.Insert);

               DataControlField[] fields = new DataControlField[this.Columns.Count];

               this.Columns.CopyTo(fields, 0);

               this.InitializeRow(row, fields);

               int index = 0;

               if (this.InsertRowPosition == RowPosition.Bottom)

               {

                   index = this.InnerTable.Rows.Count – (this.ShowFooter ? 1 : 0) – (this.AllowPaging ? 1 : 0);

               }

               else

               {          

                   // trying to add the row under the header…

                   index = this.ShowHeader ? 1 : 0;

               }

               this.InnerTable.Rows.AddAt(index, row);

           }

    protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)

           {

               if (this.EditableList)

               {

                   return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState | DataControlRowState.Edit);

               }

               else

               {

                  // allow using the grid as a "classic" grid

                   return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState);

               }

           }

  95. Sandeep kumar says:

    Matt thanks a lot.

    hey matt what i have done is i have combined both of BulkEditGridView class and FrozenHeader class and created a gridview with both of these poperties,now i want to make grid editable or no editable through a property(bool).Can u help me out how to do that with some code.

    Thanx in advance

  96. He Jiang Yuan says:

    its very helpfull to me, thanks!

  97. Anshu says:

    After installing the code How to run it?

  98. Toby says:

    If you are trying to use the validation mentioned by Jeremy on Thursday, August 24, 2006, this won’t work.  I just tested it thoroughly cause I was trying to use it.

    #1 – you can’t just loop thru dirtyrows because, after the 1st error, if the user just clicks Save again, no rows are dirty and the validation code isn’t run and the Save() method is called.

    #2 – if the user enters bad data on row 1 and enters new, correct data on row 3 (for example), you will catch the error on row 1, the user corrects row 1 and clicks Save.  But now, row has not been changed so it is not in the DirtyRows collection and UpdateRow will not be called for it.

    I haven’t coded my way out of this cul-de-sac yet but if I do, I’ll post an update.

  99. Toby says:

    update on above – I meant to say "row 3 has not been changed so it is not in the DirtyRows…"

  100. Ken says:

    This appears to be an invaluable tool and I am trying to hook it into an in-memory editing tool that allows people to edit nodes of a tree view on the fly.  Given the parameters of this tool, the actual data is being stored in a member’s profile and thus I am not technically binding the control to a data source.

    Instead, when the page first loads, I grab the appropriate node values from the Profile and display those values in editable textboxes along with boxes to alloow for deleting and dropdown boxes to allow for node-by-node option changes.

    The problem I am now facing is that I do not seem to be able to get the updated values in the code behind.  The following button is used to update the nodes:

    <asp:Button ID="btnModifyNodes" runat="server" Text="Update Nodes" CssClass="buttonClass" OnClick="btnModifyNodes_Click" />

    And I have the following start tag:

    <cc1:BulkEditGridView ID="BulkView1" SaveButtonID="btnModifyNodes"  runat="server" AutoGenerateColumns="False">

       <Columns>

            <asp:TemplateField ShowHeader="False">

                 <ItemTemplate>

                      <asp:TextBox ID="txbNode" runat="server" Text='<%# Bind("NodeText") %>’></asp:TextBox>

                 </ItemTemplate>

              </asp:TemplateField>

        </Columns>

    </cc1:BulkEditGridView>

    In the button’s click event, I have the following:

    BulkView1.Save();

    TextBox nodeBox = BulkView1.Rows[x].FindControl("txbNode") as TextBox;

    Even though I type in new words in the textbox, the value of nodeBox above is always the original value that was entered when I manually data bound the control to the Profile values.

    Can you please help?  Thank you for your time!

  101. Austin says:

    I was using the BulkEditGridView with a DropDownField and the proper value was not getting selected.  I realized it was because I had a field in my database that was type "int" and so when you do

    string val = GetValue(ctrl.NamingContainer) as string;

    that will fail or return blank or whatever it does.  So, the solution was instead of doing a cast to do a convert:

    string val = Convert.ToString(GetValue(ctrl.NamingContainer))

    This solved my problem, thought I would pass it along.

  102. Austin Grigg says:

    I am trying to figure out how I can add a required field validator to the DropDownList.  I can add the fields and I can even add the validator, but when I try to set the ControlToValidate field with the ddl.ID, it gives me an error because it says ddl.ID is blank.  I am trying to add the required field validator in InitializeDataCell.  Should I be doing something in another function?  Here is my code, any ideas?

    protected override void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState)

           {

               if((!this.ReadOnly && (0!= (rowState & DataControlRowState.Edit)))

                   || 0 != (rowState & DataControlRowState.Insert))

               {

                   DropDownList ddl = new DropDownList();

                   ddl.ToolTip = this.HeaderText;

                   if (!String.IsNullOrEmpty(this.DataField) && 0 != (rowState & DataControlRowState.Edit))

                   {

                       ddl.DataBinding += new EventHandler(HandleDataBinding);

                       ddl.DataBound += new EventHandler(HandleDataBound);

                   }

                   cell.Controls.Add(ddl);

                   if (this.ListRequiredField == true)

                   {

                       RequiredFieldValidator req1 = new RequiredFieldValidator();

                       req1.ID = "req" + ddl.ID;

                       req1.ControlToValidate = ddl.ID;

                       req1.ErrorMessage = this.ListValMessageField;

                       req1.ValidationGroup = this.ListValGroupField;

                       cell.Controls.Add(req1);

                   }

               }

               else if (!String.IsNullOrEmpty(this.DataField))

               {

                   Label lbl = new Label();

                   lbl.DataBinding += new EventHandler(HandleDataBinding);

                   cell.Controls.Add(lbl);

               }

           }

  103. Børge says:

    I’ve added some functionality to the gridview.

    1. RequiredFieldValidator is disabled in the insert-row.

    2. Delete button is removed from the insert-row.

    3. Added confirmation messagebox on the delete buttons.

    4. Preventing the gridview from crashing when there is no data, and the empty data text is not defined.

    Cheers!

  104. Børge says:

    Forgot to add the code didn’t I? 😀

    Well here goes nothin’:

    /// <summary>

           /// Creates the insert row and adds it to the inner table.

           /// </summary>

           protected virtual void CreateInsertRow()

           {

               GridViewRow row = this.CreateRow(this.Rows.Count, -1, DataControlRowType.DataRow, DataControlRowState.Insert);

               DataControlField[] fields = new DataControlField[this.Columns.Count];

               this.Columns.CopyTo(fields, 0);

               row.ApplyStyle(this.insertRowStyle);

               this.InitializeRow(row, fields);

               //Added 8.1.07 – Børge

               //Stop the gridview from crashing when no data is found, and no Empty data text is defined.

               if (this.InnerTable != null)

               {

                   int index = this.InnerTable.Rows.Count – (this.ShowFooter ? 1 : 0);

                   this.InnerTable.Rows.AddAt(index, row);

               }

               //Disable RequiredFieldValidator if present.

               //Remove delete button if present.

               for (int i = 0; i < row.Cells.Count; i++)

               {

                   for (int j = 0; j < row.Cells[i].Controls.Count; j++)

                   {

                       if (row.Cells[i].Controls[j] is RequiredFieldValidator)

                       {

                           ((RequiredFieldValidator)row.Cells[i].Controls[j]).Enabled = false;

                       }

                       else if (row.Cells[i].Controls[j] is LinkButton)

                       {

                           LinkButton linkButton = (LinkButton)row.Cells[i].Controls[j];

                           if (linkButton.CommandName.ToLower() == "delete")

                           {

                               linkButton.Enabled = false;

                               linkButton.Visible = false;

                           }

                       }

                   }

               }

           }

           /// <summary>

           /// Before a row is deleted, check if the row is empty. If so, cancel.

           /// Needs some work.. Doesn’t work when the first column has a dropDownList contol in it.

           /// Added: Cancel delete if the row is empty (indicates an insert-row).

           /// </summary>

           /// <param name="e"></param>

           protected override void OnRowDeleting(GridViewDeleteEventArgs e)

           {

               if (e.Values.Count < 1)

               {

                   e.Cancel = true;

               }

               else if (e.Values[0] == null)

               {

                   e.Cancel = true;

               }

               base.OnRowDeleting(e);

           }

           /// <summary>

           /// Adds a messageBox when delete link is clicked.        

           /// </summary>

           /// <param name="e"></param>

           protected override void OnRowDataBound(GridViewRowEventArgs e)

           {

               if (e.Row.RowType == DataControlRowType.DataRow)

               {

                   for (int i = 0; i < e.Row.Cells.Count; i++)

                   {

                       for (int j = 0; j < e.Row.Cells[i].Controls.Count; j++)

                       {

                           if (e.Row.Cells[i].Controls[j] is LinkButton)

                           {

                               LinkButton l = (LinkButton)e.Row.Cells[i].Controls[j];

                               if (l.CommandName.ToLower() == "delete")

                               {

                                   l.Attributes.Add("onclick", "javascript:return confirm(‘Are you sure you want to delete this record?’) ");

                               }

                           }

                       }

                   }                

               }

               base.OnRowDataBound(e);

           }

  105. mattdotson says:

    I’ve noticed from some of the emails I’ve gotten that people don’t see the <b>this.Response.Cache.SetCacheability(HttpCacheability.NoCache);</b> in the Global.asax.  IE sometimes doesn’t show the updates if this is not set.

  106. dbinthecountry says:

    Hi Matt,

    I am using your grid for an app that I’m working on.  It works great.  Is there a way to add custom columns such as checkboxes and dropdown lists?  Also, can the dropdowns contain data from a different datasource with the value in the gridview datasource being the one selected?  Thanks and any feedback will be greatly appreciated.

  107. finpa says:

    Is there a vb version of the bulkeditgridview source?  If not can someone walk me thru using the c# source while still maintaining vb in the code behind file.  

    Thanks!

  108. Austin says:

    I have an insert row and it will insert data, but it will not populate the dropdowns (they are there, they are just empty).  Any ideas.

  109. Jalal says:

    This is one of the best controls I ever seen. However, the ObjectDataSource still needs lot of improvement.

  110. shafiul says:

    I am trying to bind the ObjectDataSource for Dropdown list, getting below error, I tried to figure out the coz of this on different way but failed, please help:

    A field or property with the name ‘Category’ was not found on the selected data source.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Web.HttpException: A field or property with the name ‘Category’ was not found on the selected data source.

    Source Error:

    Line 123:        {

    Line 124:            Control ctrl = (Control)sender;

    Line 125:            string val = Convert.ToString(GetValue(ctrl.NamingContainer)); // as string;

  111. tomwood says:

    Despite Austin’s fix, I still had an issue with Enum as I need the value instead of the text like in:

    <select>

    <option value="1">Unit</option>

    <option value="2">Byte</option>

    </select>

    object o = GetValue(ctrl.NamingContainer);

    string val = Convert.ToString(o);

       if (o.GetType().IsEnum)

          val = ((int)o.GetType().GetField(val).GetRawConstantValue()).ToString();

    Works just fine.

  112. Asanka says:

    I also havind same problem about the validation mentioned by Jeremy on Thursday, August 24, 2006, this won’t work.  I just tested it thoroughly cause I was trying to use it.Someone also pointed out this issue.But no respond yet.Hope somebody helps me.

  113. Jiggy says:

    This is a great control, but I need to set the onchange event of the dropdown list to perform some javascript.  Is there a way to perform some client side scripting when the selected value in the drop list changes?

  114. ... says:

    luogo interessante, soddisfare interessante, buon!

  115. Stephen says:

    I want to do a bulk save and do not understand how to.  please help!

  116. Miren D says:

    I am trying to add an onlick attribute for each table cell in a row for the gridview control. I can add it for the row but haven’t been able to figure out how to add it for the individual cells. Any help would be greatly appreciated?

    protected void EditableGrid_RowCreated(object sender, GridViewRowEventArgs e)

       {

           string rowID = String.Empty;

           if (e.Row.RowType == DataControlRowType.DataRow)

           {

               rowID = "row" + e.Row.RowIndex;

               e.Row.Attributes.Add("id", "row" + e.Row.RowIndex );  

               e.Row.Attributes.Add("onclick", "ChangeRowColor(" + "’" + rowID + "’" + ")");

               string Biology = "ctl00_ContentPlaceHolder2_EditableGrid_ctl" + e.Row.RowIndex + "_ctl00" ;

               string Chemistry = "ctl00_ContentPlaceHolder2_EditableGrid_ctl" + e.Row.RowIndex + "_ctl01";

               string Physics = "ctl00_ContentPlaceHolder2_EditableGrid_ctl" + e.Row.RowIndex + "_ctl02";

               string TechEng = "ctl00_ContentPlaceHolder2_EditableGrid_ctl" + e.Row.RowIndex + "_ctl03";

    e.Row.Cells[7].Attributes.Add ("onclick", "ValidateCheck(" + "’" + Biology + "’,’" +  Chemistry + "’,’" + Physics + "’,’" + TechEng + "’" + ")") ;

               //e.Row.Cells[8].Attributes.Add("Onclick", "ValideateCheck(‘id8, id7, id9, id10)");

               //e.Row.Cells[9].Attributes.Add("Onclick", "ValideateCheck(‘id9, id7, id8, id10)");

               //e.Row.Cells[10].Attributes.Add("Onclick", "ValideateCheck(‘id10, id7, id8, id10)");

           }

       }

  117. Ninos Bisso says:

    This application is excellent, but I would like to try and get the Drop Down List working as well as the RegularExpressionValidator these would help us allot more in the future could some one please show me how to get the Drop Down LIst working and bind to a sqldatasource and the RegularExpressionValidator please please..

    This is an excellent piece of toll. Thanks Matt Dotson.

  118. ... says:

    Luogo molto buon:) Buona fortuna!

  119. ... says:

    E evidente che il luogo e stato fatto dalla persona che realmente conosce il mestiere!

  120. ... says:

    luogo interessante, soddisfare interessante, buon!

  121. ... says:

    Lo trovo piuttosto impressionante. Lavoro grande fatto..)

  122. ... says:

    Stupore! ho una sensibilit molto buona circa il vostro luogo!!!!

  123. Grace says:

    I’d like to do bulk save but only when the user leaves the page.  Can someone please help me?

    Thanks!

  124. Ginger says:

    Hi,

    First of, thank you Matt Dotson for sharing your codes.  It is extremely helpful to me.  🙂

    My problem is that, I would like to do a bulk update and make just one trip to the database.  I already have an oracle stored procedure that accepts arrays as parameters, i just need to code it in .net.  Is there a way I can do this?

    Any help I can get is highly appreciated.

    Thanks.

  125. idrees says:

    helo sir i want to add empity row at the end gridview ;

    ther are few records in grid view i have button out side gridview when i click the button it should add new empity row and i should be able to add records in that row when i finsh the adding then i will click other button named as save then it should insert record into database

    please replay me at" idrees_bit@yahoo.com" also

  126. Travis Baseflug says:

    Everything was going great with the new release and then when I drop a DDL into an edit template and set the selectedValue (from a sqldatasource) – I get the following everytime: abinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.

  127. Dk says:

    Hi,

    Is there a sample code to loop through the Controls (e.g. TextBox, DropdownList etc.) placed in the BulkEditing grid? I am not using ControlSource to bind database for select/update etc.

    I need to loop through the controls, get their values and save in the database.

    Thanks,

    DK

  128. Nix Roy says:

    Hi,

    Everyone

      Please help me out I am using a gridview and I have created links on Databound event so each row contains links to its correspondense. But while I am implemention paging. I lost links of each row. Is there any way to keep the link intact. Thanks

  129. Nix Roy says:

    Hi,

    Everyone

      Please help me out I am using a gridview and I have created links on Databound event so each row contains links to its correspondense. But while I am implemention paging. I lost links of each row. Is there any way to keep the link intact. Thanks

  130. Heather Simpson says:

    Where can I download the code for this?

    Thanks,

    Heather

  131. dil says:

    sir

     may i know how to add a new row at run time and enter values in to that row…

  132. Aideen says:

    Was the delete row functionality deliberately removed?

    AutoGenerateDeleteButton="true" adds an empty column, as does the following code:

    <asp:CommandField ShowDeleteButton="True" ControlStyle-CssClass="button" />

    I hope I’m overlooking something blatantly obvious and that someone will be able to shed some light on this for me!

  133. Eliel says:

    After few trying to do something similar, i’ve found this gridview’s extension and i think it’s great.

    Unfortunately, my requirements are just a little bigger… I’ve read almost all the comments, and found this from ndramkumar:

    "My requirement is to dynamically generate columns (Bound and Template Columns as required) in GridView control. So I need to dynamically bind the controls at runtime. I need to do a bulk update to the database from the GridView…"

    It’s exactly what i need. Since i’m setting up template columns from scracth (just like ndramkumar does), i’m loosing all gridview’s information (dataitems, columns, rows, even button’s events..).

    Anyone have found the answer to this problem?

    thanks in advance.

    Eliel (seliel@gmail.com)

  134. Joe says:

    I liked the idea of modify multiple rows at once but if you have more than one dropdown list and tons of items in each dropdown, plus the drop down is databound that really slows down performance.

  135. Ruizzie says:

    It all works pretty neat, but I am having trouble with the following scenario:

    When entering edit mode, in the RowDataBound event I set a DropDownList to the value that corresponds with the one that was present in the record.

    This causes SelectedIndexChanged to fire, which in turn causes handleRowChanged to execute, which marks the row as changed. This is unwanted behavior.

    Because the SelectedIndexChanged is hooked in the InitalizeRow method and any later does not seem to work, I see no way to initialize the DropDownList index without marking the row as changed. I can’t set the index earlier than RowDataBound and that fires way after IntializeRow.

  136. sonia says:

    Hi Everyone

    Please help me with the deletion part.. the tool is great .. but i also need to give the user an option to delete one row at a time. As mentioned earlier here in one of the blogs the delete button even if added is creating an empty column…Kindly help ..

  137. sonia says:

    Hi

    The deletion part is an urgent requirement please share the solution soon.

  138. Sam says:

    Hi! Matt,

    Great work!

    I have a quick question: How to change the text box width of the Grid view? I changed the width through item style, but did not find the text box width get changed.

  139. Daryl says:

    First of all, thanks for the great controls.  They’ve been very useful to me.  I ran across an issue today that I’m not sure I understand.  I’m using a BulkEditGridView. I’m calling Save() in the handler for the SelectedIndexChanged event on a DropDownList.  The problem is that HandleRowChanged doesn’t get called on the BulkEditGridView until after the SelectedIndexChanged event has already been handled, so when I call Save(), there are no dirty rows.  Maybe this is just an order of events in ASP.NET that I’m not familiar with.  If you can shed any light on this, that would be great.  Below is my code:

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

    <%@ Register Assembly="RealWorld.Grids" Namespace="RealWorld.Grids" TagPrefix="cc1" %>

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

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

    <head runat="server">

       <title>Untitled Page</title>

    </head>

    <body>

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

       <div>

           <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

               <asp:ListItem>1</asp:ListItem>

               <asp:ListItem>2</asp:ListItem>

               <asp:ListItem>3</asp:ListItem>

           </asp:DropDownList>

           <cc1:BulkEditGridView ID="BulkEditGridView1" runat="server" AutoGenerateColumns="False"

               DataSourceID="sqldsTest" EnableInsert="False" SaveButtonID="">

               <Columns>

                   <asp:BoundField DataField="username" HeaderText="username" ReadOnly="True" SortExpression="username" />

                   <asp:CheckBoxField DataField="immersive" HeaderText="immersive" SortExpression="immersive" />

               </Columns>

           </cc1:BulkEditGridView>

           <asp:SqlDataSource ID="sqldsTest" runat="server" ConnectionString="<%$ ConnectionStrings:CMDPortalConnectionString %>"

               SelectCommand="SELECT [username], [immersive] FROM [STUDENT_PROJECT_PARTICIPANT] WHERE (([project_id] = @project_id) AND ([reporting_period] = @reporting_period))"

               UpdateCommand="INSERT INTO TEST (data1, data2)&#13;&#10;VALUES (@username, @immersive)">

               <UpdateParameters>

                   <asp:ControlParameter ControlID="BulkEditGridView1" Name="username" PropertyName="SelectedValue" />

                   <asp:ControlParameter ControlID="BulkEditGridView1" Name="immersive" PropertyName="SelectedValue" />

               </UpdateParameters>

               <SelectParameters>

                   <asp:Parameter DefaultValue="22" Name="project_id" Type="Int32" />

                   <asp:Parameter DefaultValue="7" Name="reporting_period" Type="Int32" />

               </SelectParameters>

           </asp:SqlDataSource>

       </div>

       </form>

    </body>

    </html>

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

    {

       protected void Page_Load(object sender, EventArgs e)

       {

       }

       protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

       {

           BulkEditGridView1.Save();

       }

    }

  140. Nabin says:

    Thanks a lot.. That really helped

  141. faizal says:

    hi thanks  for this  one

    but can u send  in a  vb.NET

  142. Umit Khanna says:

    Hi,

    I need to add a link in a column in grid view control. Now the issue is that it should come only, when the data is availiable for that link.

    so what I want to do it, I want to write a query in that column to know the count(*),if its greather than 0 only then the link will come.

    Now writing the query here results in an error, because it says ‘Eval("Id")’can’t be used without a server control.

    So, pls help me and let me know how to resolve this.

    Thanks in advance.

    Umit Khanna

  143. wabster says:

    Hi,

    I tried adding extra functionality to the BulkEditGrid that would allow me to transfer between a bulkeditgrid and an edit grid.  I was looking to have a regular grid that when I click an edit BUTTON on the page it will change the grid to a bulk edit grid.

    To do so I added the following Property to BulkEditGrid:

    Private b_Edit As Boolean = False

           Public Property EditMode() As Boolean

               Get

                   Return b_Edit

               End Get

               Set(ByVal value As Boolean)

                   b_Edit = value

               End Set

           End Property

    then I also modified CreateRow with an if statement:

           Protected Overrides Function CreateRow(ByVal rowIndex As Integer, ByVal dataSourceIndex As Integer, ByVal rowType As System.Web.UI.WebControls.DataControlRowType, ByVal rowState As System.Web.UI.WebControls.DataControlRowState) As System.Web.UI.WebControls.GridViewRow

               If EditMode = True Then

                   Return MyBase.CreateRow(rowIndex, dataSourceIndex, rowType, DataControlRowState.Edit)

               Else

                   Return MyBase.CreateRow(rowIndex, dataSourceIndex, rowType, DataControlRowState.Normal)

               End If

           End Function

    On my ASPX page, on the click event for my button I added code such as:

           If beg2.EditMode = False Then

               beg2.EditMode = True

               beg2.DataBind()

           Else

               beg2.EditMode = False

               beg2.DataBind()

           End If

    On the first click once the page is refreshed it works fine changing the gridview.  However, on any subsequent clicks it doesn’t work.  It is still reading beg2.editmode as the initial value that it was when the page was first loaded.  Am I doing something wrong or does anyone have a way around it.

  144. wabster says:

    noticed a little typo.  I want it to transfer between all fields static and all fields editable (like a regular gridview to a bulkeditgrid).

    Hi,

    I tried adding extra functionality to the BulkEditGrid that would allow me to transfer between a bulkeditgrid and the standard format of the gridview.  I was looking to have a regular grid that when I click an edit BUTTON on the page it will change the grid to a bulk edit grid.

    To do so I added the following Property to BulkEditGrid:

    Private b_Edit As Boolean = False

          Public Property EditMode() As Boolean

              Get

                  Return b_Edit

              End Get

              Set(ByVal value As Boolean)

                  b_Edit = value

              End Set

          End Property

    then I also modified CreateRow with an if statement:

          Protected Overrides Function CreateRow(ByVal rowIndex As Integer, ByVal dataSourceIndex As Integer, ByVal rowType As System.Web.UI.WebControls.DataControlRowType, ByVal rowState As System.Web.UI.WebControls.DataControlRowState) As System.Web.UI.WebControls.GridViewRow

              If EditMode = True Then

                  Return MyBase.CreateRow(rowIndex, dataSourceIndex, rowType, DataControlRowState.Edit)

              Else

                  Return MyBase.CreateRow(rowIndex, dataSourceIndex, rowType, DataControlRowState.Normal)

              End If

          End Function

    On my ASPX page, on the click event for my button I added code such as:

          If beg2.EditMode = False Then

              beg2.EditMode = True

              beg2.DataBind()

          Else

              beg2.EditMode = False

              beg2.DataBind()

          End If

    On the first click once the page is refreshed it works fine changing the gridview.  However, on any subsequent clicks it doesn’t work.  It is still reading beg2.editmode as the initial value that it was when the page was first loaded.  Am I doing something wrong or does anyone have a way around it.

  145. wabster says:

    I think I figured it out.  It was all a matter of losing state, so I changed the property to the following:

           Public Property EditMode() As Boolean

               Get

                   Return CBool(ViewState(b_Edit))

               End Get

               Set(ByVal value As Boolean)

                   ViewState(b_Edit) = value

               End Set

           End Property

    Does it sound right that state needs to be maintained for these controls?  

  146. Prasad says:

    I was trying to change the datasource at runtime, (changed the select, insert and update statement) for the SQLdatasource, the select command works at page load for once. If I change the select statement in SQLDataSource, the bulk edit grid showing blank data. Can Any One help me out.

  147. FeGu says:

    I have the same controls you want.  A regular grid and a bulk edit.  simply bind both to the same dataset.  Once an update is performed on the bulk edit, rebind the read only and hide the bulkedit.  Simple…

  148. FeGu says:

    One of my users noticed that when modifying/adding records, if they click some where else causing post backs then…when saving… suff on the grid get’s lost.  What I found is that rows don’t show as dirty or as newRows and are completely ignored.

    Has anyone found a solution to this?

    Regards!

  149. Joe says:

    The dirtyRow list and newRows list are not persisted in ViewState. Therefore, any postback causes them to be initialized to empty.

    To get around this, I added an override for SaveViewState() where I dump the list to viewstate. I then wrapped the dirtyRow in a property that loads from viewstate when it is initialized. Now I’m about to do the same for newRow.

  150. TomD says:

    I discovered the same problem with the dirtyRows and newRows loosing the state between postbacks (doing server side validation in a click event). The following code inserted in BulkEditGridView.cs did it for me:

           protected override object SaveViewState()

           {

               object[] state = new object[3];

               state[0] = base.SaveViewState();

               state[1] = this.dirtyRows;

               state[2] = this.newRows;

               return state;

           }

           protected override void LoadViewState(object savedState)

           {

               object[] state = null;

               if (savedState != null)

               {

                   state = (object[])savedState;

                   base.LoadViewState(state[0]);

                   this.dirtyRows = (List<int>) state[1];

                   this.newRows = (List<int>) state[2];

               }

           }

  151. MichaelN says:

    Thanks for the SaveViewState example.  Was able to modify it to work in my VB version.

    Sample of code I used is below (please note that I’m not using newRows in my GridView, so excluded that particular object from the code).

           Protected Overrides Function SaveViewState() As Object

               Dim state(2) As Object

               state(0) = MyBase.SaveViewState()

               state(1) = Me.dirtyRows

               Return state

           End Function

           Protected Overrides Sub LoadViewState(ByVal savedState As Object)

               If Not (savedState Is Nothing) Then

                   Dim state() As Object = savedState

                   MyBase.LoadViewState(state(0))

                   Me.dirtyRows = state(1)

               End If

           End Sub

  152. Jagan says:

    Hi Matt,

    Thanks a lot for this sample. It has been very useful in my project and I’m using it for very complex business logic. Only challenge I’m seeing with this when inserting multiple rows with paging enabled. I am not sure whether this supports multiple rows as your original sample works with one new row at a time. It would be great if you can include the paging and then multiple row insertion.

    Thanks again.

    Jagan

  153. Travich says:

    Here’s what I don’t get — the changed events are firing, which is server code.  So we’re doing postbacks right, or is there an ajax component to this that I’m not seeing.  I’m referring to multiple row edits.  FYI.

  154. David Alge says:

    I just downloaded the code and implemented into my project and it works great! It was exactly what I was looking for. One thing that I would like to do, but either it isn’t supported or lack of knowledge in the use of your component, but I would like for it to save the data when clicking on any of the pages (if paging is enabled). Other than that, everything works great!

    David

  155. Fred says:

    Is the tab index working right? Does the focus go in a normal order from one cell to the next horizontally on each row?

  156. medtun.net says:

    I have a problem with DataFormatString, the formatting can’t be applied to some fields. in my case {0:d} and {0:t} don’t work!

    Thanks.

  157. medtun.net says:

    I solved the problem. Every thing is ok. Great control.

    Thanks.

  158. pakornss says:

    Could I use like this?

    protected void gridView_DataBinding(object sender, EventArgs e)

    {

    GridView gv = (GridView)sender;

    foreach(DataColumn dataField in gv.Columns)

    {

     if( dataField is TemplateField)

     {

       TemplateField tp = (TemplateField)gv.Columns[i];

               tpItemTemplate = tp.EditItemTemplate;

     }

    }

    }

  159. DaveS says:

    I have the grid popluating okay with data.  I am using a DataSet as my source. When I make an update to a column in the grid and click the Update button and Save()is called I am getting an error then this code is fired:

    this.UpdateRow(row, false);

    The error is:

    The GridView ‘EditableGrid’ fired event RowUpdating which wasn’t handled.

    I have not made any changes to BulkEditGridView.cs, so did I miss something? Anyone know why this error is happening?  I am coding in VS 2005.

    Thanks.

  160. Marco says:

    Dear,

    thx for the excellent tool, did you already solve the CompareAllValues issue where all the original values are null when saving?

    also, i have 2 dropdowns that are used as a filter for the gridview, apparently the datasource of the bulk gridview is filled first before the 2 dropdowns, can this order be changed?

  161. marcocuyt says:

    for my second problem: the selecting event of this bulkedit gridview came before the selecting event of other objectdatasources where the gridview depends on (eg: 2 dropdowns and the gridview needs these 2 values for its own data)

    the problem was the overridden onload event of the gridview, if you override the oninit event, the problem is solved…

  162. marcocuyt says:

    ok forget it, with the oninit event no dirty row is created…<sigh>

  163. Burton says:

    To Delete a rec just add a button col and set it’s command name to delete <asp:ButtonField CommandName="delete" Text="Button" />. Of course your dataSource will need… "DeleteCommand="DELETE FROM….." Love the BulkEditGridView!!!

  164. Steve says:

    I have a similar issue, but it relates to sorting while editing. If I begin editing a row, and then resort the gridview when I hit the updae button I am saving the data to the wrong row. Do you know any way to fix this problem?

  165. Jeff says:

    How do I access the TextBox through the backend. I need to do this through the backend. Is there a way to do this?

  166. Justin says:

    I have just started using the grid control and it is great.  However, I want to insert a new row into the bulk edit gridview control by clicking a button on the web form.

    Any help would be great.

    Thanks~

  167. Adam says:

    If anyone is still searching for a way to get values into your DropDownField on the Insert row, I’ve hooked into the InitializeRow method.  If it’s the Insert row, just loop through all the controls and call DataBind on them.  If they’re DataBound, it works…if not, swallow the exception.

  168. I am trying to use DropDown with BulkEditGrid-Insert Grid, in an update mode.

    1. The dropdown does not populate with the existing value of grid row.

    2. The dropdown doesn’t get populated for new empty row of data

  169. M.Daud says:

    wow, thats a great control. i luv it

  170. Janaka says:

    My Gridview is bound to ICollection. My previous update function is like this.

      Dim dgi As GridViewRow

           For Each dgi In DataGrid1.Rows

               Dim LateHours As String = CType(dgi.FindControl("txtLateHours"), TextBox).Text

               Dim LateMins As String = CType(dgi.FindControl("txtLateMins"), TextBox).Text

               Dim ErrorMsg As CustomValidator = CType(dgi.FindControl("CustLateHours"), CustomValidator)

               If LateMins = "00" Or LateMins = "0" Or LateMins = " " Then

                   If LateHours > 12 Then

                       ErrorMsg.ErrorMessage = "Late Hours should be less than 12"

                       args.IsValid = False

                   Else

                       ErrorMsg.ErrorMessage = ""

                   End If

               Else

                   If LateHours > 11 Then

                       ErrorMsg.ErrorMessage = "Late Hours should be less than 12"

                       args.IsValid = False

                   Else

                       ErrorMsg.ErrorMessage = ""

                   End If

               End If

           Next

           disableandenable()

       End Sub

       Protected Sub DataGrid1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles DataGrid1.PageIndexChanging

           Page.Validate()

           If Page.IsValid Then

               DataGrid1.PageIndex = e.NewPageIndex

               getData()

           End If

       End Sub

       Protected Sub DataGrid1_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles DataGrid1.RowCreated

           If e.Row.RowType = ListItemType.Item Or e.Row.RowType = ListItemType.AlternatingItem Or e.Row.RowType = ListItemType.SelectedItem Then

               e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=’#C2DFFF’;this.style.cursor=’hand’")

               e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=’white’;")

           End If

           If e.Row.RowType = ListItemType.AlternatingItem Or _

           e.Row.RowType = ListItemType.Item Then

               e.Row.Cells(13).ToolTip = "Edit"

           ElseIf e.Row.RowType = ListItemType.EditItem Then

               e.Row.Cells(13).ToolTip = "Update and Cancel"

               e.Row.Cells(14).ToolTip = "Overtime should be less than 4 in week days and 10 in weekends and holidays"

           End If

           ‘ e.Item.Cells(16).Attributes.Add("OnChange", "document.form1.txtOverTime.disabled = true;")

           disableandenable()

           ShowDay()

       End Sub

       Protected Sub DataGrid1_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles DataGrid1.RowEditing

           Response.Write("gdgdfgg")

       End Sub

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

           For Each dgi In DataGrid1.Rows

               Dim OTHours As String = CType(dgi.FindControl("txtOTHours"), TextBox).Text

               Dim OTMins As String = CType(dgi.FindControl("txtOTMins"), TextBox).Text

               ‘Sanction01

               Dim Sanction01 As String = CType(dgi.FindControl("ddSanction"), DropDownList).SelectedValue

               ‘LateHours

               Dim LateHours As String = CType(dgi.FindControl("txtLateHours"), TextBox).Text

               Dim LateMins As String = CType(dgi.FindControl("txtLateMins"), TextBox).Text

               ‘Sanction02

               Dim Sanction02 As String = CType(dgi.FindControl("ddSanction2"), DropDownList).SelectedValue

               ‘Status

               Dim Status As String = CType(dgi.FindControl("ddlStatus"), DropDownList).SelectedValue

               ‘Remarks

               Dim Remarks As String = CType(dgi.FindControl("ddlRemarks"), DropDownList).SelectedValue

               Dim OwnRemarks As String = CType(dgi.FindControl("txtRemarks"), TextBox).Text

               ‘Emp_Code

               Dim EmpCode As Integer = CType(dgi.FindControl("lblEmpCode"), Label).Text

               ‘Date

               Dim Day As DateTime = CType(dgi.FindControl("lblDate"), Label).Text

               Dim weekday As String = Day.DayOfWeek.ToString()

               ‘define parameters

               Dim ParamOTHours As New SqlParameter("@OTHours", SqlDbType.VarChar, 4)

               ParamOTHours.Direction = ParameterDirection.Input

               If Len(OTHours) = 1 Then

                   ParamOTHours.Value = "0" + OTHours

               ElseIf Len(OTHours) = 0 Then

                   ParamOTHours.Value = "00"

               Else

                   ParamOTHours.Value = OTHours

               End If

               Dim ParamOTMins As New SqlParameter("@OTMins", SqlDbType.VarChar, 4)

               ParamOTMins.Direction = ParameterDirection.Input

               If Len(OTMins) = 1 Then

                   ParamOTMins.Value = "0" + OTMins

               ElseIf Len(OTMins) = 0 Then

                   ParamOTMins.Value = "00"

               Else

                   ParamOTMins.Value = OTMins

               End If

               Dim ParamSanction1 As New SqlParameter("@Sanction1", SqlDbType.VarChar, 10)

               ParamSanction1.Direction = ParameterDirection.Input

               ParamSanction1.Value = Sanction01

               Dim ParamLateHours As New SqlParameter("@LateHours", SqlDbType.VarChar, 4)

               ParamLateHours.Direction = ParameterDirection.Input

               If Len(LateHours) = 1 Then

                   ParamLateHours.Value = "0" + LateHours

               ElseIf Len(LateHours) = 0 Then

                   ParamLateHours.Value = "00"

               Else

                   ParamLateHours.Value = LateHours

               End If

               Dim ParamLateMins As New SqlParameter("@LateMins", SqlDbType.VarChar, 4)

               ParamLateMins.Direction = ParameterDirection.Input

               If Len(LateMins) = 1 Then

                   ParamLateMins.Value = "0" + LateMins

               ElseIf Len(LateMins) = 0 Then

                   ParamLateMins.Value = "00"

               Else

                   ParamLateMins.Value = LateMins

               End If

               Dim ParamSanction2 As New SqlParameter("@Sanction2", SqlDbType.VarChar, 10)

               ParamSanction2.Direction = ParameterDirection.Input

               ParamSanction2.Value = Sanction02

               Dim ParamStatus As New SqlParameter("@Status", SqlDbType.VarChar, 10)

               ParamStatus.Direction = ParameterDirection.Input

               ParamStatus.Value = Status

               Dim ParamRemarks As New SqlParameter("@Remarks", SqlDbType.VarChar, 20)

               ParamRemarks.Direction = ParameterDirection.Input

               ‘ If OwnRemarks = "Or Enter your own Remarks" Then

               ‘ParamRemarks.Value = Remarks

               If Remarks <> "Select from the List" Then

                   ParamRemarks.Value = Remarks

               Else

                   ParamRemarks.Value = OwnRemarks

               End If

               Dim ParamEmpCode As New SqlParameter("@EmpCode", SqlDbType.BigInt)

               ParamEmpCode.Direction = ParameterDirection.Input

               ParamEmpCode.Value = EmpCode

               Dim ParamDate As New SqlParameter("@Date", SqlDbType.DateTime)

               ParamDate.Direction = ParameterDirection.Input

               ParamDate.Value = Day

               ‘ reading the connection string from web.config file

               strconn = ConfigurationManager.AppSettings("ZulTimeConnectionString1")

               ‘ for opening db connection

               Dim Con As New SqlConnection(strconn)

               Dim UpdateCmd As SqlCommand = New SqlCommand("UpdateTimeSheet", Con)

               UpdateCmd.CommandType = CommandType.StoredProcedure

               UpdateCmd.Parameters.Add(ParamOTHours)

               UpdateCmd.Parameters.Add(ParamOTMins)

               UpdateCmd.Parameters.Add(ParamSanction1)

               UpdateCmd.Parameters.Add(ParamLateHours)

               UpdateCmd.Parameters.Add(ParamLateMins)

               UpdateCmd.Parameters.Add(ParamSanction2)

               UpdateCmd.Parameters.Add(ParamStatus)

               UpdateCmd.Parameters.Add(ParamRemarks)

               UpdateCmd.Parameters.Add(ParamEmpCode)

               UpdateCmd.Parameters.Add(ParamDate)

               Con.Open()

               Try

                   UpdateCmd.ExecuteNonQuery()

               Catch ex As Exception

                   UserMsgBox(ex.Message)

               End Try

               ‘Connection Object Creation

               Con.Close()

           Next

    But from here each and every row is updating. That is why I need to use this custom gridview control. Can anyone give me help to customize my update function according to this.

    Thanks,

    Janaka.

  171. Smurph says:

    I tried making this more ‘real-world’ by not binding to an sqldatasource at design-time but rather to an array of objects in code usng datasource and databind(), e.g customers. Now none of the change event handlers work so there are never any dirty rows….

    HELP!! Surely someone else has noticed this? I do not like using the design time datasource controls!!

  172. nutan says:

    BulkeditGridView is working fine. Although I cam across one problem, in a row I have two fields which are textboxes with style="display:none". I am changing value of these two fields on the change of value of field outside BulkeditGridView and on the serverside. But this is not setting dirtyRows. Can anyone explain why?

  173. Eman says:

    Thanks alot for yiur effort this is incredibly useful!!! iu was this close to giving up on my website and switching to windows forms until i found this code so thanks

  174. Eman says:

    i tried using the grid, all the cells were editable which is good. but the save button is not doing anything ! i ended up writing my pwn update code. I wonder if I’m doing something wrong. I took the compiled dll from :

    http://www.codeplex.com/ASPNetRealWorldContr/Release/ProjectReleases.aspx?ReleaseId=1674

    and just dragged it to my project and assigned the datasource. is anyone having the same problem ?

  175. Kamesh says:

    please let me know,how to get the index of a row in a gridview where the linkbutton as an item template ,clicked is present

  176. Kythor says:

    Eman, can you give me your update code, I’m looking for the same thing

  177. Mike says:

    Is there a memory limit for using Real World GridView? I’ve had it working with great results for 2 years and suddenly it is crashing. I am populating it from an Access Database and if I split up the query into 2 smaller ones it works fine, but with returning anything over 40 rows (15 odd fields per row) it crashes. Under 40 rows it works fine?

  178. Eman says:

    Kythor ,

    I just wrote my own stored procedure to update the data in teh tables. the tricky part was how to get the data from the cells. this is what I used:

    ‘ for read only cells:

    Dim product As String = frtGrid.Row(RowIndex).Cells(1).Text

    Dim priceCell As TextBox = CType(frtGrid.Rows(RowIndex).Cells(10).Controls(0), TextBox)

    dim product as string = productCell.text

  179. HD says:

    It’s great !!!

    Can I get the VB version of RealWordGrids.zip?

    Thanks,

  180. HD says:

    Hi,

    First of all, thanks for this great tool.

    I have downladed RealWordGrids.zip and testing it for my application. I have a problem with DropDownList if it is Integer. In this sample, State codes are char(2) so it’s working fine but integer doesn’t. My test codes are following quotes. (ItemId is Integer in my table).

    Would anyone please advise me how to solve this?

    Thanks,

                       <rwg:DropDownField HeaderText="Item" DataField="itemid" ListDataValueField="itemid" ListDataTextField="Description" ListDataSourceID="sdsItems" />

       <asp:SqlDataSource ID="sdsItems" runat="server" ConnectionString="<%$ ConnectionStrings:MyDB %>"

           SelectCommand="SELECT [ItemID], [Description] FROM [Item]"></asp:SqlDataSource>

  181. Kenneth Mazur says:

    Matt,

    This is awesome.  I’m trying to create the Edit Everything button in the same way you did the Save button.  But not sure how to programmatically do the override on the EditButtonID click.  Do you have an example of that somewhere?

    Thanks

  182. ep says:

    How do you programmatically add/insert rows to a BulkEditGridView?

    I have set EnableInsert=true and InsertRowCount=1, but once the user has completed that row with insert values, they want to click ‘add row’ to add another blank row. Is this possible?

  183. Mohit says:

    Matt, that’s a great control.

    I needed to allow the use of arrow keys for navigation. I added the handlekey event to the textbox in rowdatabound eventhandler.

    handlekey is the javascript method.

           function handleKey(evt)

           {

               // This method allows the navigation using arrow keys in the gridview textbox

               evt = (evt) ? evt : ((window.event) ? event : null);

               var str = evt.srcElement.name;

               var strGridName = str.slice(0,str.indexOf("$ctl"));

               var returnValue = true;

               var col = str.slice(str.lastIndexOf("$ctl")+4);

               var row = str.slice(str.indexOf("$ctl")+4,str.lastIndexOf("$ctl"));    

               var rowNum = parseInt(row,10);

               var colNum = parseInt(col,10);

               var newFieldName = "";

               var newTextBox = null;

               switch (evt.keyCode) {

                   case 40:

                       // Down Key

                   newFieldName = strGridName + "$ctl"+formatNumberToString(rowNum+1,row)+"$ctl"+col;

                       break;    

                   case 39:

                       // Right Key

                       if(currentCursorPos(evt.srcElement)>=evt.srcElement.value.length){

                       newFieldName = strGridName + "$ctl"+row+"$ctl"+formatNumberToString(colNum+1,col);

                       returnValue = false;

                   }

                       break;    

                   case 38:

                       // Up Key

                   newFieldName = strGridName + "$ctl"+formatNumberToString(rowNum-1,row)+"$ctl"+col;

                       break;    

                   case 37:

                       // Left Key

                       if(0==currentCursorPos(evt.srcElement)){

                           newFieldName = strGridName + "$ctl"+row+"$ctl"+formatNumberToString(colNum-1,col);

                       returnValue = false;

                   }

                       break;    

               }

           newTextBox = document.getElementById(newFieldName);

           if(null != newTextBox)

               newTextBox.focus();

               return returnValue;

           }

           function formatNumberToString(number, string)

           {

               // returns 01 for (1,00); 0004 for (4,0003)

               var strNumber = "" + number;

               while(strNumber.length < string.length){

                   strNumber = "0" + strNumber;

               }

               return strNumber;

           }

    // Thanks to Yann-Erwan Perio for caret position method        

           function currentCursorPos(el)

           {

               var sel, rng, r2, i=-1;

               if(typeof el.selectionStart=="number") {

                   i=el.selectionStart;

               } else if(document.selection && el.createTextRange) {

                   sel=document.selection;

                   if(sel){

                       r2=sel.createRange();

                       rng=el.createTextRange();

                       rng.setEndPoint("EndToStart", r2);

                       i=rng.text.length;

                   }

               } else {

                   el.onkeyup=null;

                   el.onclick=null;

               }

               return i;

           }

    These functions adds the excel like navigation using arrow keys.

  184. Fabi says:

    Hi,

    I am using BulkeditGridview, On save of the grid, am able to validate for dirty rows for existing data. but not on insert of new rows.

    Please guide me how to go about validation for New insert rows which are null or blank string and validate for integer. and show the alert in javascript? on save

    Thank you,

    Fabi

  185. Sita says:

    Iam using BulkeditGridview but I dont know how to validate the new rows inserted.Can you please help me out how to get the values inserted in a new row before save?

  186. Chris B says:

    HD:

    I had a similar problem when my DropDownField used an integer for the value & a string for the text. I changed one line in DropDownField.cs to explicity convert the gridview cell’s value to a string like this:

    void HandleDataBound(object sender, EventArgs e)

           {

               Control ctrl = (Control)sender;

               string val = System.Convert.ToString(GetValue(ctrl.NamingContainer));

               DropDownList ddl = ctrl as DropDownList;

               if (null != ddl)

               {

                   //make sure the appropriate value is selected

                   ListItem li = ddl.Items.FindByValue(val);

                   if (null != li)

                   {

                       li.Selected = true;

                   }

               }

           }

    I’m a C# newbie, so I could be missing something…. but it worked!

  187. Eric Schwartz says:

    Is there a way to change the taborder within this control from horizontal to vertical?  I would like to tab down one column and then the next instead of across the row.

  188. Rino says:

    Hi,

    i have added a property :

           private bool pEditMode;

           public bool EditMode

           {

               get

               {

                   return pEditMode;

               }

               set

               {

                   pEditMode = value;

               }

           }

    and in rowcreate event i replace your code with:

           protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)

           {

               if (pEditMode)

                  return base.CreateRow(rowIndex, dataSourceIndex, rowType, rowState | DataControlRowState.Edit);

               else

                  return base.CreateRow(rowIndex, dataSourceIndex, rowType, DataControlRowState.Normal);

           }

    why :

    1. grid always in editmode even though the property Window i set editmode = false

    2. if i set property in the server-side code, when build, return this error :

    Error 1 ‘RealWorld.Grids.BulkEditGridView’ does not contain a definition for ‘EditMode’ and no extension method ‘EditMode’ accepting a first argument of type ‘RealWorld.Grids.BulkEditGridView’ could be found (are you missing a using directive or an assembly reference?)

  189. Harshad Nayani says:

    This is nice article for refence

  190. Harshad says:

    This is nice article for refence

  191. Is it easy to use this GridView with a

    <asp:LinqDataSource>?

  192. megasoft78 says:

    Hi all,

    I wrote an article on how create BulkEdit on GridView without DataSource control.

    This is the link:

    http://www.codeproject.com/KB/webforms/BulkEditGridView.aspx

  193. snow says:

    how can i set default parameters in bulkeditgridview?pls

  194. snow says:

    how can i control the each cell of bulkeditgrid.

    i want to validate each cell and also add new row in selected date..pls

  195. Shayek says:

    How can i get the selected index from a GridView by using hyperlink for a specific column insted of using Select option….?

  196. Ritchie says:

    Excellent control – thanks. Do you have any suggestions as to how values could be "dragged down" in a similar way to Excel?

  197. Aaron says:

    I just downloaded the source and see that you have created a GridView for each of the different features you have talked about in your articles and wonder why you would not implement all the features in one grid?

  198. OnlyLiu says:

    FullyEditableGridViewinASP.NET2usingC#

  199. Edwin says:

    Hi all,

    I am fresh to ASP.NET.

    Actually i take few weeks time already to search for solution to update dropdownlist.selectedvalue into database. I search google and forum but i still cant figure out the real solution. And, finally i search to this page, I drop a msg here and hope someone can share their solution with their source code explanation. I will really appreciate if someone may  help me.

  200. Hard to know without seeing source code, but I’m going to guess you haven’t declared either the DataKeyNames or the SaveButtonId of the gridview.

  201. Rignet says:

    Hi Matt,

    Very nice article. I have a question for you. I am new to Gridview and am building a application with a Datbound Gridview using Bulk Editing. The gridview has 3 columns (id, ListPrice,SalesPrice). What I would like to do is to use a textbox and a button where I can put in discount, say 50% in the textbox and hit the button and the SalesPrice column will be filled out based on the ListPrice column. Any idea or sample code would be appreciated.

  202. rozz says:

    Why are the insert rows not available in the GridViewRowCollection?  I am validating an insert row and I cannot find any means to access that row in my c# code behind.

    For validation, my approach is to include RequiredFieldValidators in the EditItemTemplate.  Set the default enabled value of the validators to false and then in the RowDataBound event, go ahead and enable the validators.  This makes it so all of the rows are validated except for the insert rows.  This works nicely because if nothing is entered in the insert row, the rest of the GridView is validated and saved.  Without this disabling/enabling approach, the insert row is always validated even if you are only editing an existing row.  Now, I need to be able to access the insert row on the save button event handler, validate the textboxes, then manually call Save().

    Any thoughts?  Is there any way that I can get to the InnerTable in my code behind because I can’t use the GridViewRowCollection?  Thanks.

  203. Eric says:

    How can I get the new values of specific cells in my gridview, so that I can write my own upate code on the click event of the SaveButton. I need to write the changes out to multiple tables…

    thanks

  204. Benjiman says:

    Hi,

    Its a excellent solution with a lot enhancement in last few years.

    Im a beginner of vb. I had tried to traslate the code to vb, however, i got some problems in below

    ___________________________________________________

    ddl.DataBindig += New EventHandler(HandleDataBinding)

    ddl.DataBound += New EventHandler(HandleDataBound)

    lbl.DataBinding += New EventHandler(HandleDataBinding)

    __________________________________________________

    Could anyone help me work with it

    thanks

  205. Jimbo says:

    The code in C#:

    -> ddl.DataBinding += New EventHandler(HandleDataBinding)

    In VB this becomes:

    -> AddHandler bForecast.DataBinding, AddressOf HandleDataBinding

    Not entirely intuitive, but a common conversion.

  206. anbaz says:

    Hi All,

    I want to inplement template column with <asp:ImageButton> , is it possible?

  207. gridview sorting says:

    i bind one gridview name as gv1 column is 5 column [1 column is edit command].i click edit then clicked the row value change in another gridview name is gv2 but first column is sorting how to write

  208. Marco says:

    Hi all,

    is there a way to fix the empty dropdownlist, into the ‘new record’ row? thanks

  209. Jeff says:

    I love this setup, it works well. I am having a problem though with one issue. I am trying to insert another header line which I have no problem doing on a regular gridview. Any ideas? I want to be able ad a row above the header row for grouping. Here is my code and the satement e.Row.Parent.Controls.AddAt(0, row) is failing. I am executing this via GetMyMultiHeader(e) on rowcreated event. Any help would be greatly appreciated.

       Public Sub GetMyMultiHeader(ByVal e As GridViewRowEventArgs)

           If e.Row.RowType = DataControlRowType.Header Then

               ‘the following is to add multiple column headers to the gridview

               Dim createCells As SortedList = New SortedList()

               createCells.Add("0", ",2,1")

               createCells.Add("1", "Item Information,5,1")

               createCells.Add("2", "Current Forecast Qty,6,1")

               createCells.Add("3", "Forecast History Qty,6,1")

               createCells.Add("4", "Sales History Qty (12 months),4,1")

               createCells.Add("5", "Sales History Qty (current season),5,1")

               createCells.Add("6", "Current Forecast $,6,1")

               createCells.Add("7", "Forecast History $,6,1")

               createCells.Add("8", "Sales History $ (12 months),4,1")

               createCells.Add("9", "Sales History $ (current season),5,1")

               Dim row As GridViewRow

               Dim EnumCels As IDictionaryEnumerator = createCells.GetEnumerator()

               Dim cont As String()

               row = New GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal)

               While EnumCels.MoveNext()

                   cont = EnumCels.Value.ToString().Split(Convert.ToChar(","))

                   Dim Cell As TableCell

                   Cell = New TableCell()

                   Cell.RowSpan = Convert.ToInt16(cont(2).ToString())

                   Cell.ColumnSpan = Convert.ToInt16(cont(1).ToString())

                   Cell.Controls.Add(New LiteralControl(cont(0).ToString()))

                   Cell.HorizontalAlign = HorizontalAlign.Center

                   If EnumCels.Key = 0 Then

                       Cell.ForeColor = Drawing.Color.Black

                       Cell.BackColor = Drawing.Color.Black

                   End If

                   If EnumCels.Key = 1 Then

                       Cell.ForeColor = Drawing.Color.White

                       Cell.BackColor = Drawing.Color.DarkBlue

                   End If

                   If EnumCels.Key = 2 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.Plum

                   End If

                   If EnumCels.Key = 3 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.LightBlue

                   End If

                   If EnumCels.Key = 4 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.LightGray

                   End If

                   If EnumCels.Key = 5 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.LawnGreen

                   End If

                   If EnumCels.Key = 6 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.Plum

                   End If

                   If EnumCels.Key = 7 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.LightBlue

                   End If

                   If EnumCels.Key = 8 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.LightGray

                   End If

                   If EnumCels.Key = 9 Then

                       Cell.ForeColor = Drawing.Color.Blue

                       Cell.BackColor = Drawing.Color.LawnGreen

                   End If

                   row.Cells.Add(Cell)

               End While

               Try

                   e.Row.Parent.Controls.AddAt(0, row)

               Catch

                   MsgBox("Add Row Failed")

               End Try

           End If

       End Sub

  210. andré says:

    Talking about "Real GridView :

    It mists a "GrivFull" indication somewhere.

    I’ll wash the legs of the "saint homme" who’ll write

    a méthod to calculate the remaining memory

    as filling the gridview !

  211. Mauro says:

    MOHIT where did you add the handleKey event? Can you post an example? That’s very interesting I need an "exel-like" GridView as well!!

    Thanks in advance

  212. Disha says:

    hi all! m disha, and new to asp.net. I am working in a project named online shopping cart. When i clicked AddToCart button on Product.aspx, the row details are tranferred to cart.aspx, when i again go to Product.aspx and add another product in the list, the previous one is lost in cart.aspx, i have to maintain a session for this purpose, on both the pages details of products are bounded in gridview. So could somebody help me out!,how could it be done.

  213. Wire says:

    If I save this code to a .vb file in my add_code directory named bulkedit.vb how do I access it in a normal .aspx page.  Using Register doesn’t appear to be working.

  214. Rebecca says:

    I love this tool.  But I am having trouble getting a rangevalidators inside the edit template to work.  

    I can loop through and programatically add my minimum and maximum ranges (dob and current date) to the rangevalidators.  I do this on a button click (no savebuttonid), then want to use if page.isvalid then Editablegrid.save.  

    But isValid always comes back true.  If I manually compare the values I can set IsValid to false, but I’m afraid I’m making more trouble for myself that way.

  215. Rebecca says:

    Forgot to add – doesn’t work if I put dummy values in the aspx page for min and max value, either.

  216. Rebecca says:

    Well, I think I got my rangevalidators to work.  Probably simple to everyone else.  If I’ve made it more complicated than necesasry, then sorry.  Put this in the prerender event after creating the rangevalidtors in the edit template (visible, btw):

    Dim trow As GridViewRow

           For Each trow In EditableGrid.Rows

               Dim rowX As Integer

               rowX = trow.RowIndex

               Dim Rgv1 As RangeValidator

               Rgv1 = CType(EditableGrid.Rows(rowX).FindControl("Rvaletxtdate1"), RangeValidator)

               Rgv1.MaximumValue = Date.Today.ToShortDateString()

               Rgv1.MinimumValue = CType(Session("dob"), Date).ToShortDateString()

    Next

  217. I have a simple question.... says:

    How do I create the custom control and afterwords add it to the page?

    Thank you.

  218. Pete Long says:

    Hi Matt,

    I’m new to .NET and this was just what i was looking for. It works great when the class code is in the App_Code folder in the website, but having gone through the effort of creating a .DLL and adding it to the Bin folder, it no longer works? I get compile errors? I didn’t get any errors when I compiled the code to create the .DLL. Any ideas?

    Anyhow thanks for the original post, it was excellent…

    Rgds, Pete…

  219. Afroditi says:

    Hi Matt, your article is almost perfect!!!I’m new to ASP.NET and it was very helpfully!My question is…how can we get the value from a specific cell.I use GridView.Rows(i).Cells(j).Text

    and gives me "".It gets a value only for read-only columns and not for editable cells!Plz give me a help!

  220. Stephany says:

    I made one of my columns a template column so that I would be able to do validation, but I get the following error:

    Callbacks are not supported on TemplateField because some controls cannot update properly in a callback.  Turn callbacks off on ‘BulkEditGridView1’.

    It happens on the following line:

    protected override void PerformSelect() {

    Line 88: if (!isSaving) base.PerformSelect();

  221. Iris Shalev says:

    Hi, Matt.

    I am trying to expand you Editable Grid, and make it edetable only for Enabled rows + rows I select.

    I created CheckBoxes in my GridView, named CBSelect.

    Then, I wrote this code into you function:

    protected override GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState)

    {

    if (rowType == DataControlRowType.DataRow)

    {

      if ((this.Rows.Count > 0) && (rowIndex >-1)

         && (dataSourceIndex > -1))

      {

        if (this.Rows[rowIndex].Enabled == true)

        {

          bool enabled=this.Rows[rowIndex].Enabled;

         CheckBox cbSelect = this.Rows

    [rowIndex].FindControl("cbSelect") as CheckBox;

          if (cbSelect ==null)

          {

             return base.CreateRow

                        (rowIndex,dataSourceIndex,

                         rowType, rowState |

                         DataControlRowState.Edit);

          }

          else

          {

             if ((cbSelect.Checked == true) &&

                 (this.Rows[rowIndex].Enabled))

             {

                return base.CreateRow(rowIndex,

                dataSourceIndex, rowType, rowState

                | DataControlRowState.Edit);

             }

             else

             {

                 return base.CreateRow(rowIndex,

                 dataSourceIndex, rowType,

                 rowState);

              }

          }

        }

      }

    }

    }

    The controle code compiles but the control itself is not renderred in my application.

    The error I recieve when I try to switch views in my aspx file is:

    "There was an error rendering the control.

    Index was out of rande. Must be  A non-negative and less than the size of the collection. Parameter Name: index".

    I tried everything and recieved the same result.

    Could you please help me?

    Thanks,

      Iris.

  222. Afroditi says:

    Hi…again!I found the way to get value from editable cell: CType(GridView.Rows(i).FindControl("ID"), TextBox).

    You have to convert the fields into TemplateFields first.

    Now…i need help to read the value after user change this. CType(GridView.Rows(i).FindControl("ID"), TextBox)give the first value from datasource.Could someone help me?

  223. Afroditi says:

    hello..there..!Finally the way to get user’s value is the above,if you insert the right "ID" :-).

    Well,the reason i want these values is to use them for calculations and not for updating(at the begging-if user likes these then he clicks "update").(vb)

    Dim Txt1 As TextBox

    Dim STxt1 As String

    Dim Txt2 As TextBox

    Dim STxt2 As String

    Dim Txt_result As TextBox

    Dim pre_result As Double

    Dim result As Double

    Protected Sub btnCalc_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalc.Click

    Txt1 = CType(GridView1.Rows(1).FindControl("Txt1"), TextBox)

    STxt1 = Txt1.Text

    Txt2 = CType(GridView1.Rows(1).FindControl("Txt2"), TextBox)

    STxt2 = Txt2.Text

    pre_result = (Convert.ToDouble(Txt1) + Convert.ToDouble(Txt2)) / 2

    result = 0.6*pre_result

    Txt_result = CType(GridView1.Rows(1).FindControl("Txt3"), TextBox)

    Txt_result.Text = result.ToString

    End Sub

    My problem is that at the user’s FIRST btnCalc_Click after – > End Sub it goes (i don’t understand why) to CreateRow function and create the rows again so the user’s values disappeared!!!It happens only at the first user’s click.

    At the 2nd,3d etc when user insert values and click the button everything it’s ok!!!

    Plzzzzzzz someone help me!!!!

  224. Abhishek says:

    I have read through the blog and the comments

    gave copied BulkEditGridView.cs to App_Code folder, modified the web.config file to add

    <pages>

           <controls>

             <add  assembly="RealWorld.Grids" namespace="RealWorld.Grids" tagPrefix="rwg" />

           </controls>

         </pages>

    the Gridview aspx tags have been changed to <rwg:BulkEditGridView></rwg:BulkEditGridView>

    still i get the error

    Error 15 Could not load file or assembly ‘RealWorld.Grids’ or one of its dependencies. The system cannot find the file specified.

  225. FWIW, here’s my take on a bulk edit grid (except mine is actually a listview):

    http://programmerramblings.blogspot.com/2008/09/full-edit-dynamic-listview-aka.html

  226. P.Muthu raj says:

    Real World GridView:  Bulk Editing not bind dat form 250 ”’; For 150 Rows  it takes 3 to 4 minuts; i am using 34 colums

    How to rectify

  227. AB says:

    I really like '<sarcasm>minor</sarcasm>' part, u r coool 🙂

  228. Abu says:

    Thanks for the extended control.  I have downloaded it and populated it with DATA.  I see the textboxes.  Now, I would like to fire my own update function,  how to fire my update function and check for those updated rows?

    Thanks

  229. Matt Algate says:

    Need New "EVENT" gv_AfterUpdate (ALL)

    Tried to hold off on existing gv_afterupdate by using session item reset after ALL rows done – but the gv event is complete before the session item is set to "done"

    ON PAGE:

    ————–

       Protected Sub gvTicketListing_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles gvTicketListing.RowUpdated

    –>        If Session.Item("UpdateDone") = "TRUE" Then

               DoAfterRWGSave()

    –>            Session.Item("UpdateDone") = "False"

           End If

       End Sub

    ON NWSS in APP_CODE:

    ———————————–

           Public Sub save()

    –>            Dim Session As System.Web.SessionState.HttpSessionState = HttpContext.Current.Session

    –>            Session.Item("UpdateDone") = "False"

               For Each row As Integer In dirtyRows

                   Me.UpdateRow(row, False)

               Next

               dirtyRows.Clear()

    –>            Session.Item("UpdateDone") = "TRUE"

           End Sub

  230. Leo says:

    To the ones who don't know how to INSTALL the BulkEditGridView control in Visual Studio, here goes a nice tutorial 🙂

    dhavalupadhyaya.wordpress.com/…/how-to-add-custom-control-in-visual-studio-toolbox

  231. Richard says:

    Please can someone tell me if it is possible to have the bulkeditgridview in read only mode?

    I want to put it into bulk edit mode when the user clicks the edit button.

  232. frank says:

    How would I handle – "the grid to not be editable until the user clicks an "edit everything" button."?

    This is some really good work!  Thanks in advance!!

  233. Marc says:

    I'm trying to use this wonderful control, but I"m having a problem.  The DirtyRows funtionality doesn't seem to be working.  Every visible row updates when I save the changes, as opposed to just the rows I've changed.  Can you suggest what I"m doing wrong?

  234. Hi Matt says:

    Great stuff there Matt, was thinking of adding one more (part 4?) request for your gridview to become exactly what anyone would want to use …..it would be nice within the columns of your gridview that you add a property that says to have editable mode or not, sort of like have a textbox (or control) view, and readonly becoming a lable view only, but per column, so you can control which columns are editable and which arent…and also, at some point, you could take this down, and start selling your little component for 5$ if you packaged it properly to allow for ease of use…just a thought.

  235. David ben Pinchas says:

    Hi,

    I am trying to use the BulkEditGridView, but have a problem: the execution never comes to HandleRowChanged() when I change values, thus the data never gets updated. Could you please help me with this?

    Thanks.

  236. UpdateModel (e.NewValues) says:

    Hi, great article.  I'm using a custom datasource as IList<T>.  I have new values, but is there a way to simlpy have the new values update my model?  I can use reflection but I thought the two way data binding using Bind("field") – would auomaticlly update my session source with values.  Im trying to find a simple way of doing this in the rowupdating method… so when save is called, I can tryupdate on objects that are dirty in my business layer (note: we're using EF 4.1 so I want my object to be updated directly from e.newvalues.

    thanks

    Marty

  237. e.newValues to business object says:

    Hi, great article.  I'm using a custom datasource as IList<T>.  I have new values, but is there a way to simlpy have the new values update my model?  I can use reflection but I thought the two way data binding using Bind("field") – would auomaticlly update my session source with values.  Im trying to find a simple way of doing this in the rowupdating method… so when save is called, I can tryupdate on objects that are dirty in my business layer (note: we're using EF 4.1 so I want my object to be updated directly from e.newvalues.

    thanks

    Marty

  238. nath says:

    Hi everyone,

    Where is the source for this article?

    thanks

    nath

  239. Vikas says:

    Hi Matt,

    Could you please post the code to edit the all the gridview rows on click of a button.

  240. Vikas says:

    Hi Matt,

    Could you please post the code to edit all the gridview rows on click of a button.

    Thanks,

    Vikas