Welcome to MSDN Blogs Sign in | Join | Help

Matt Dotson's .NET Tips & Tricks

The posts on this weblog are provided "AS IS" with no warranties, and confer no rights. The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
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

Posted: Wednesday, November 09, 2005 8:54 AM by mattdotson

Attachment(s): RealWorldGrids.zip

Comments

Sunish Abraham said:

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
# November 10, 2005 10:44 AM

SBrickey said:

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
# November 21, 2005 2:44 PM

mattdotson said:

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.
# November 22, 2005 4:43 AM

Trav said:

Any chance of getting a vb version for lowly vb.net programmers?
# November 30, 2005 7:44 PM

Khuzema said:

any chance to get a source project. regards
# December 14, 2005 10:51 AM

Michael said:

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!
# December 16, 2005 5:03 PM

Harry Verstandig said:

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.
# February 26, 2006 1:11 PM

Matt's .NET Tips & Tricks said:

Let's take a look at some real world uses for GridView.
# March 1, 2006 10:38 PM

Matt's .NET Tips & Tricks said:

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
# March 1, 2006 11:11 PM

mattdotson said:

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.
# March 2, 2006 3:45 AM

mark r. reynolds said:

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  

# March 2, 2006 10:37 PM

P said:

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
# March 3, 2006 5:20 AM

mattdotson said:

P, it's under the source control section of the workspace. $/RealWorld.Grids/BulkEditGridView.cs
# March 3, 2006 2:06 PM

mattdotson said:

Thanks Mark.  I think I understand your issue, and will investigate it.  If I find a solution, I will post it here.
# March 3, 2006 2:13 PM

mattdotson said:

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

James said:

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!
# March 12, 2006 11:33 AM

James said:

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.
# March 12, 2006 4:28 PM

sirisha said:

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
 
# March 21, 2006 11:31 AM

cc said:

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)
# March 21, 2006 1:04 PM

Matt said:

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
# March 26, 2006 10:08 PM

brian said:

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
# March 29, 2006 5:36 PM

Cliff said:

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
# March 30, 2006 6:45 AM

Brian said:

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.
# March 30, 2006 12:00 PM

Cliff said:

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
# March 30, 2006 3:37 PM

Cliff said:

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
# March 31, 2006 3:41 AM

Eric D. said:

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?
# April 6, 2006 2:35 PM

Scott C said:

How hard would it be to implement templated Columns so that you could have validators and such?
# April 6, 2006 3:52 PM

John M said:

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).
# April 12, 2006 11:58 PM

Scott said:

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?
# April 18, 2006 2:52 PM

Christian Lebon said:

This is very cool.  What would really take this to the next level is if you added the code to insert new rows
# April 24, 2006 1:34 AM

Bill said:

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
# April 26, 2006 12:56 PM

CC said:

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.
# April 27, 2006 4:54 PM

CliffMitchell said:

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
# April 30, 2006 9:23 AM

Thiru said:

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

Thanks,

Thiru
# May 4, 2006 2:18 PM

Dan said:

I am also trying to find the source code for this. Please excuse me as I am a newbie to the ASP.net world.
# May 4, 2006 5:26 PM

Matt Dotson said:

I have updated the BulkEditGridView to fix the EmptyDataText problem.  Thanks Cliff!!
# May 4, 2006 11:26 PM

Matt Dotson said:

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.
# May 5, 2006 1:32 AM

Dan C said:

I have posted a VB version on the gotdotnet workspace. Can somone help with the testing
# May 8, 2006 2:10 PM

Diego said:

Great controls!!!!

Is there a release in C#?
# May 9, 2006 5:28 AM

Christian Lebon said:

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
# May 9, 2006 4:32 PM

Steve said:

Happy to test - tell me how to find it!
# May 9, 2006 11:13 PM

Christian Lebon said:

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.
# May 10, 2006 3:20 AM

Chagel's Home said:

# May 17, 2006 2:52 AM

mattdotson said:

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.
# May 17, 2006 11:34 PM

Diego said:

> 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
# May 18, 2006 3:31 AM

Christian said:

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.
# May 18, 2006 3:11 PM

Joe said:

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
# May 19, 2006 11:38 AM

Elizabeth said:

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.  
# May 22, 2006 1:12 PM

mattdotson said:

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.
# May 25, 2006 2:39 AM

molhokwai said:

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...
# May 30, 2006 4:24 AM

Lars said:

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?
# May 31, 2006 10:24 AM

Amino said:

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
# June 15, 2006 11:58 AM

ShaunR said:

Great blog, and controls..thanks!
# June 16, 2006 11:31 AM

なんとかblog said:

先日ObjectDataSource,ObjectDataSourceViewを...
# June 20, 2006 12:20 PM

Phil said:

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.
# June 21, 2006 3:40 PM

rosy said:

its very helpfull to us thankx
# July 1, 2006 2:20 AM

Srinivasa Raghavan said:

how to do bulk update of rows using  sqldatasource control.
# July 7, 2006 12:23 PM

WadeC said:

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
# July 12, 2006 8:56 PM

ndramkumar said:

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();
       }
 
   }



# July 26, 2006 1:45 AM

Jurjen de Groot said:

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
# August 1, 2006 10:11 AM

Roy DA said:

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...
# August 2, 2006 1:45 PM

k.ekezie said:

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?
# August 3, 2006 11:20 AM

Jay said:

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
# August 9, 2006 12:31 PM

Adam said:

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!!!
# August 10, 2006 9:37 AM

Ram said:

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
# August 10, 2006 3:57 PM

Fearson said:

your article is very usefull to me,thanks a lot
# August 11, 2006 12:51 PM

Ulysses said:

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..
# August 15, 2006 10:44 PM

Miguel said:

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.
# August 20, 2006 10:53 AM

Dave said:

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?
# August 21, 2006 12:41 PM

Jeff said:

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);
       }
# August 21, 2006 2:19 PM

Dave said:

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.
# August 21, 2006 5:07 PM

Jeffry said:

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

Thanks,

Jeffry
# August 23, 2006 11:05 AM

Miguel said:

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?
# August 23, 2006 1:36 PM

Jeremy Fuller said:

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>
# August 24, 2006 11:26 PM

Seetapati said:

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?
# September 9, 2006 3:54 PM

Shahzad Godil said:

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

# October 16, 2006 2:23 PM

Shahzad Godil said:

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

# October 16, 2006 2:25 PM

Tomer said:

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

# October 17, 2006 3:56 PM

Binod said:

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

# October 20, 2006 3:38 PM

LSUgirl said:

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.

# October 23, 2006 5:24 PM

simon said:

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

# October 24, 2006 5:02 AM

Harry said:

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

# October 26, 2006 11:44 AM

Jesper said:

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

# October 30, 2006 10:58 AM

Judah said:

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

# October 30, 2006 6:11 PM

Jesper said:

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

# November 2, 2006 8:02 AM

Evgueni said:

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

# November 7, 2006 6:57 PM

Ron Delzer said:

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);

           }

       }

# November 9, 2006 2:48 PM

Jit said:

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).

# November 13, 2006 2:15 AM

Vincent D'Souza said:

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

# November 13, 2006 9:48 AM

Sarasu said:

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" >

               <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();

# November 14, 2006 1:58 PM

Boerge said:

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);

}

# November 23, 2006 5:03 AM

Vivek said:

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

# November 23, 2006 8:09 AM

amit said:

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

# November 28, 2006 1:03 AM

Javier Cabrera said:

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.

# December 14, 2006 4:27 PM

Christophe Vigouroux said:

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);

           }

       }

# December 18, 2006 1:10 PM

Sandeep kumar said:

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

# December 20, 2006 10:44 PM

He Jiang Yuan said:

its very helpfull to me, thanks!

# December 25, 2006 12:14 AM

Anshu said:

After installing the code How to run it?

# December 29, 2006 6:53 PM

Toby said:

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.

# January 8, 2007 5:59 PM

Toby said:

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

# January 8, 2007 6:01 PM

Ken said:

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" />

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!

# January 13, 2007 9:02 PM

Austin said:

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.

# January 17, 2007 1:44 PM

Austin Grigg said:

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);

           }

       }

# January 22, 2007 9:22 AM

Børge said:

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!

# January 24, 2007 5:15 AM

Børge said:

Forgot to add the code didn't I? :-D

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);

       }

# January 24, 2007 5:17 AM

mattdotson said:

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.

# January 24, 2007 6:18 AM

dbinthecountry said:

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.

# January 31, 2007 5:34 PM

finpa said:

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!

# February 5, 2007 8:59 AM

Austin said:

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.

# February 9, 2007 3:49 PM

Jalal said:

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

# February 10, 2007 6:01 AM

shafiul said:

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;

# February 12, 2007 10:49 PM

tomwood said:

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.

# February 13, 2007 9:22 AM

Asanka said:

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.

# February 24, 2007 12:38 AM

Jiggy said:

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?

# March 1, 2007 9:31 AM

... said:

luogo interessante, soddisfare interessante, buon!

# March 5, 2007 4:58 AM

Stephen said:

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

# March 5, 2007 2:34 PM

Miren D said:

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)");

       }

   }

# March 8, 2007 1:47 PM

Ninos Bisso said:

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.

# March 9, 2007 1:16 AM

... said:

Luogo molto buon:) Buona fortuna!

# March 10, 2007 4:32 PM

... said:

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

# March 13, 2007 7:13 AM

... said:

luogo interessante, soddisfare interessante, buon!

# March 15, 2007 5:10 PM

... said:

Lo trovo piuttosto impressionante. Lavoro grande fatto..)

# March 17, 2007 11:40 AM

... said:

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

# March 19, 2007 2:48 AM

Grace said:

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

Thanks!

# March 29, 2007 10:12 AM

Ginger said:

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.

# April 3, 2007 11:35 AM

idrees said:

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

# April 11, 2007 3:43 AM

Travis Baseflug said:

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.

# April 13, 2007 10:58 AM

Dk said:

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

# April 17, 2007 4:41 PM

Nix Roy said:

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

# April 19, 2007 11:16 AM

Nix Roy said:

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

# April 19, 2007 11:16 AM

Heather Simpson said:

Where can I download the code for this?

Thanks,

Heather

# April 25, 2007 1:14 AM

dil said:

sir

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

# April 30, 2007 5:54 AM

Aideen said:

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!

# May 15, 2007 7:04 AM

Eliel said:

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)

# May 30, 2007 8:30 PM

Joe said:

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.

# June 7, 2007 4:23 PM

Ruizzie said:

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.

# June 13, 2007 4:30 AM

sonia said:

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 ..

# June 15, 2007 6:39 AM

sonia said:

Hi

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

# June 15, 2007 7:03 AM

Sam said:

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.

# June 25, 2007 3:38 PM

Daryl said:

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">

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

<head runat="server">

   <title>Untitled Page</title>

</head>

<body>

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

   <div>

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

           <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();

   }

}

# July 13, 2007 10:08 AM

Nabin said:

Thanks a lot.. That really helped

# July 22, 2007 7:13 PM

faizal said:

hi thanks  for this  one

but can u send  in a  vb.NET

# July 25, 2007 6:36 AM

Umit Khanna said:

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

# July 30, 2007 2:34 AM

wabster said:

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.

# August 3, 2007 3:12 PM

wabster said:

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.

# August 3, 2007 3:21 PM

wabster said:

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?  

# August 6, 2007 1:05 PM

Prasad said:

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.

# August 13, 2007 12:47 AM

FeGu said:

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...

# August 14, 2007 9:21 AM

FeGu said:

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!

# August 14, 2007 9:24 AM

Joe said:

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.

# August 23, 2007 12:53 PM

TomD said:

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];

           }

       }

# August 26, 2007 10:54 PM

MichaelN said:

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

# September 25, 2007 12:13 PM

Jagan said:

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

# October 5, 2007 1:17 PM

Travich said:

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.

# October 8, 2007 5:37 PM

David Alge said:

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

# October 9, 2007 5:26 PM

Fred said:

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

# October 16, 2007 9:04 PM

medtun.net said:

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.

# October 22, 2007 11:16 AM

medtun.net said:

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

Thanks.

# October 23, 2007 4:30 AM

pakornss said:

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;

 }

}

}

# October 31, 2007 5:41 AM

DaveS said:

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.

# October 31, 2007 1:51 PM

Marco said:

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?

# November 1, 2007 3:11 PM

marcocuyt said:

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...

# November 2, 2007 6:38 AM

marcocuyt said:

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

# November 2, 2007 6:44 AM

Burton said:

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!!!

# November 2, 2007 11:49 AM

Steve said:

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?

# November 5, 2007 2:17 PM

Jeff said:

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

# November 12, 2007 4:04 AM

Justin said:

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~

# November 12, 2007 9:16 AM

Adam said:

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.

# November 12, 2007 5:51 PM

Vaishali Rane said:

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

# November 20, 2007 4:17 PM

M.Daud said:

wow, thats a great control. i luv it

# November 24, 2007 7:51 AM

Janaka said:

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.

# November 26, 2007 7:16 AM

Smurph said:

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!!

# January 10, 2008 8:46 PM

nutan said:

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?

# January 14, 2008 3:08 PM

Eman said:

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

# January 29, 2008 12:12 AM

Eman said:

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 ?

# January 29, 2008 4:38 AM

Kamesh said:

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

# March 5, 2008 4:01 AM

Kythor said:

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

# March 10, 2008 9:07 AM

Mike said:

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?

# March 18, 2008 7:18 PM

Eman said:

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

# March 27, 2008 5:46 AM

HD said:

It's great !!!

Can I get the VB version of RealWordGrids.zip?

Thanks,

# April 4, 2008 10:14 AM

HD said:

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>

# April 6, 2008 1:17 AM

Kenneth Mazur said:

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

# April 9, 2008 8:24 AM

ep said:

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?

# May 9, 2008 12:03 PM

Mohit said:

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.>

               el.>

           }

           return i;

       }

These functions adds the excel like navigation using arrow keys.

# May 11, 2008 11:59 PM

Fabi said:

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

# May 12, 2008 8:03 AM

Sita said:

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?

# May 13, 2008 1:34 AM

Chris B said:

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!

# May 13, 2008 2:54 PM

Eric Schwartz said:

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.

# May 29, 2008 9:49 AM

Rino said:

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?)

# June 4, 2008 5:55 AM

Harshad Nayani said:

This is nice article for refence

# June 16, 2008 4:19 PM

Harshad said:

This is nice article for refence

# June 16, 2008 4:19 PM

Sillion Nightfrost said:

Is it easy to use this GridView with a

<asp:LinqDataSource>?

# June 17, 2008 4:50 AM

megasoft78 said:

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

# June 17, 2008 4:24 PM

snow said:

how can i set default parameters in bulkeditgridview?pls

# June 23, 2008 2:24 AM

snow said:

how can i control the each cell of bulkeditgrid.

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

# June 23, 2008 11:21 PM

Shayek said:

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

# July 6, 2008 8:45 AM

Ritchie said:

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

# July 7, 2008 8:52 AM

Aaron said:

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?

# July 9, 2008 1:29 PM

OnlyLiu said:

FullyEditableGridViewinASP.NET2usingC#

# July 11, 2008 5:19 AM

Edwin said:

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.

# July 22, 2008 12:24 PM

FrugalGuitarist.com said:

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.

# July 24, 2008 11:19 AM

Rignet said:

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.

# August 4, 2008 1:04 PM

rozz said:

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.

# August 18, 2008 12:35 AM

Eric said:

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

# August 22, 2008 2:13 PM

Benjiman said:

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

# August 27, 2008 5:30 AM

Jimbo said:

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.

# September 9, 2008 2:26 PM

anbaz said:

Hi All,

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

# September 11, 2008 11:32 PM

gridview sorting said:

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

# September 24, 2008 4:40 AM

Marco said:

Hi all,

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

# October 24, 2008 12:32 PM

Jeff said:

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

# November 11, 2008 8:38 PM

andré said:

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 !

# December 2, 2008 6:42 AM

Mauro said:

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

# December 8, 2008 6:29 AM

Disha said:

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.

# December 19, 2008 5:01 AM
Leave a Comment

(required)

(required)

(optional)

(required)

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker <> </htm