Welcome to MSDN Blogs Sign in | Join | Help

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

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

Attachment(s): RealWorldGrids.zip

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

Comments

# re: Extending ASP.NET's GridView: Bulk Editing

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
Thursday, November 10, 2005 10:44 AM by Sunish Abraham

# re: Extending ASP.NET's GridView: Bulk Editing

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

# re: Extending ASP.NET's GridView: Bulk Editing

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

# re: Extending ASP.NET's GridView: Bulk Editing

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

# re: Extending ASP.NET's GridView: Bulk Editing

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

# re: Extending ASP.NET's GridView: Bulk Editing

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

# re: Extending ASP.NET's GridView: Bulk Editing

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.
Sunday, February 26, 2006 1:11 PM by Harry Verstandig

# Real World GridView: Two Headed &amp;amp; Grouping GridViews

Let's take a look at some real world uses for GridView.
Wednesday, March 01, 2006 10:38 PM by Matt's .NET Tips & Tricks

# Finally ... Part 2 of Real World GridViews

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
Wednesday, March 01, 2006 11:11 PM by Matt's .NET Tips & Tricks

# re: Real World GridView: Bulk Editing

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.
Thursday, March 02, 2006 3:45 AM by mattdotson

# re: ObjectDataSource CompareAllValues Issue

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  

Thursday, March 02, 2006 10:37 PM by mark r. reynolds

# re: Real World GridView: Bulk Editing

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
Friday, March 03, 2006 5:20 AM by P

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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?
Thursday, April 06, 2006 2:35 PM by Eric D.

# re: Real World GridView: Bulk Editing

How hard would it be to implement templated Columns so that you could have validators and such?
Thursday, April 06, 2006 3:52 PM by Scott C

# Release a Server Control?

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).
Wednesday, April 12, 2006 11:58 PM by John M

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

Thanks,

Thiru
Thursday, May 04, 2006 2:18 PM by Thiru

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

I have updated the BulkEditGridView to fix the EmptyDataText problem.  Thanks Cliff!!
Thursday, May 04, 2006 11:26 PM by Matt Dotson

# re: Real World GridView: Bulk Editing

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.
Friday, May 05, 2006 1:32 AM by Matt Dotson

# re: Real World GridView: Bulk Editing

I have posted a VB version on the gotdotnet workspace. Can somone help with the testing
Monday, May 08, 2006 2:10 PM by Dan C

# re: Real World GridView: Bulk Editing

Great controls!!!!

Is there a release in C#?
Tuesday, May 09, 2006 5:28 AM by Diego

# re: Real World GridView: Bulk Editing

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
Tuesday, May 09, 2006 4:32 PM by Christian Lebon

# re: Test VB Version

Happy to test - tell me how to find it!
Tuesday, May 09, 2006 11:13 PM by Steve

# re: Real World GridView: Bulk Editing

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.
Wednesday, May 10, 2006 3:20 AM by Christian Lebon

# 也谈GridView

Wednesday, May 17, 2006 2:52 AM by Chagel's Home

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

Great blog, and controls..thanks!
Friday, June 16, 2006 11:31 AM by ShaunR

# GridViewとObjectDataSource

先日ObjectDataSource,ObjectDataSourceViewを...
Tuesday, June 20, 2006 12:20 PM by なんとかblog

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

its very helpfull to us thankx
Saturday, July 01, 2006 2:20 AM by rosy

# re: Real World GridView: Bulk Editing

how to do bulk update of rows using  sqldatasource control.
Friday, July 07, 2006 12:23 PM by Srinivasa Raghavan

# re: Real World GridView: Bulk Editing

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

# Real World GridView: Bulk Editing

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



Wednesday, July 26, 2006 1:45 AM by ndramkumar

# re: Real World GridView: Bulk Editing

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
Tuesday, August 01, 2006 10:11 AM by Jurjen de Groot

# re: Real World GridView: Bulk Editing

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...
Wednesday, August 02, 2006 1:45 PM by Roy DA

# re: Real World GridView: Bulk Editing

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?
Thursday, August 03, 2006 11:20 AM by k.ekezie

# re: Real World GridView: Bulk Editing

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
Wednesday, August 09, 2006 12:31 PM by Jay

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

# re: Real World GridView: Bulk Editing

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

Thanks,

Jeffry
Wednesday, August 23, 2006 11:05 AM by Jeffry

# re: Real World GridView: Bulk Editing

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

# Validating the BulkEditingGridView control

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>
Thursday, August 24, 2006 11:26 PM by Jeremy Fuller

# re: Real World GridView: Bulk Editing

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?
Saturday, September 09, 2006 3:54 PM by Seetapati

# re: Real World GridView: Bulk Editing

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

Monday, October 16, 2006 2:23 PM by Shahzad Godil

# re: Real World GridView: Bulk Editing

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

Monday, October 16, 2006 2:25 PM by Shahzad Godil

# Bulk Editing without 'Bulk' controls?

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

Tuesday, October 17, 2006 3:56 PM by Tomer

# re: Real World GridView: Bulk Editing

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

Friday, October 20, 2006 3:38 PM by Binod

# re: Real World GridView: Bulk Editing

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.

Monday, October 23, 2006 5:24 PM by LSUgirl

# re: Real World GridView: Bulk Editing

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

Tuesday, October 24, 2006 5:02 AM by simon

# re: Real World GridView: Bulk Editing

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

Thursday, October 26, 2006 11:44 AM by Harry

# re: Real World GridView: Bulk Editing

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

Monday, October 30, 2006 10:58 AM by Jesper

# re: Real World GridView: Bulk Editing

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

Monday, October 30, 2006 6:11 PM by Judah

# Adding HeaderRow when no data exists in gridview and only new row exists in gridview

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

Thursday, November 02, 2006 8:02 AM by Jesper

# re: Real World GridView: Bulk Editing

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

Tuesday, November 07, 2006 6:57 PM by Evgueni

# re: Real World GridView: Bulk Editing

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

           }

       }

Thursday, November 09, 2006 2:48 PM by Ron Delzer

# re: Real World GridView: Bulk Editing

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

Monday, November 13, 2006 2:15 AM by Jit

# re: Real World GridView: Bulk Editing

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

Monday, November 13, 2006 9:48 AM by Vincent D'Souza

# re: Real World GridView: Bulk Editing

Need Help!!!

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

My aspx page code for gridcontrol

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

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

               <Columns>

               <asp:TemplateField HeaderText="ID">

<ItemTemplate>

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

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

        </asp:HyperLink>

</ItemTemplate>

</asp:TemplateField>

       <asp:TemplateField HeaderText="ReleaseDate">

       <ItemTemplate>

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

      </ItemTemplate>

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

       </asp:TemplateField>

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

           <ItemStyle HorizontalAlign="Center" />

       </asp:BoundField>    

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

           <ItemStyle HorizontalAlign="Center" />

       </asp:BoundField>

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

           <ItemStyle HorizontalAlign="Center" />

       </asp:BoundField>

               </Columns>

           </rwg:BulkEditGridView>

my codebehind coded

 DataSet DetailsDS = GetDetails.GetDetails(InputXML);

       GridView2.DataSource = DetailsDS;

       GridView2.DataBind();

Tuesday, November 14, 2006 1:58 PM by Sarasu

# re: Real World GridView: Bulk Editing

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

}

Thursday, November 23, 2006 5:03 AM by Boerge

# Paging poses a problem

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

Thursday, November 23, 2006 8:09 AM by Vivek

# re: Real World GridView:

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

Tuesday, November 28, 2006 1:03 AM by amit

# Customizing by columns

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.

Thursday, December 14, 2006 4:27 PM by Javier Cabrera

# Insert Row at the top of the grid instead of at the bottom

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

           }

       }

Monday, December 18, 2006 1:10 PM by Christophe Vigouroux

# re: Real World GridView: Bulk Editing

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

Wednesday, December 20, 2006 10:44 PM by Sandeep kumar

# re: Real World GridView: Bulk Editing

its very helpfull to me, thanks!

Monday, December 25, 2006 12:14 AM by He Jiang Yuan

# re: Real World GridView: Bulk Editing

After installing the code How to run it?

Friday, December 29, 2006 6:53 PM by Anshu

# re: Validation

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.

Monday, January 08, 2007 5:59 PM by Toby

# re: Validation

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

Monday, January 08, 2007 6:01 PM by Toby

# Bulk Editing Unbound

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

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

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

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

And I have the following start tag:

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

   <Columns>

        <asp:TemplateField ShowHeader="False">

             <ItemTemplate>

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

             </ItemTemplate>

          </asp:TemplateField>

    </Columns>

</cc1:BulkEditGridView>

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

BulkView1.Save();

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

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

Can you please help?  Thank you for your time!

Saturday, January 13, 2007 9:02 PM by Ken

# Solution to DDL not choosing SelectedValue

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.

Wednesday, January 17, 2007 1:44 PM by Austin

# Adding RequiredFieldValidator

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

           }

       }

Monday, January 22, 2007 9:22 AM by Austin Grigg

# Removing Validator and delete button from insert row ++

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!

Wednesday, January 24, 2007 5:15 AM by Børge

# Removing Validator and delete button from insert row ++

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

       }

Wednesday, January 24, 2007 5:17 AM by Børge

# re: Real World GridView: Bulk Editing

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.

Wednesday, January 24, 2007 6:18 AM by mattdotson

# re: Real World GridView: Bulk Editing

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.

Wednesday, January 31, 2007 5:34 PM by dbinthecountry

# re: Real World GridView: Bulk Editing

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!

Monday, February 05, 2007 8:59 AM by finpa

# Insert Row Doesn't Populate Drop Downs

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.

Friday, February 09, 2007 3:49 PM by Austin

# re: Real World GridView: Bulk Editing

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

Saturday, February 10, 2007 6:01 AM by Jalal

# re: Real World GridView: Bulk Editing

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;

Monday, February 12, 2007 10:49 PM by shafiul

# re: Solution to DDL not choosing SelectedValue

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.

Tuesday, February 13, 2007 9:22 AM by tomwood

# re: Real World GridView: Bulk Editing

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.

Saturday, February 24, 2007 12:38 AM by Asanka

# re: Real World GridView: Bulk Editing

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?

Thursday, March 01, 2007 9:31 AM by Jiggy

# re: Real World GridView: Bulk Editing

luogo interessante, soddisfare interessante, buon!

Monday, March 05, 2007 4:58 AM by ...

# re: Real World GridView: Bulk Editing

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

Monday, March 05, 2007 2:34 PM by Stephen

# re: Real World GridView: Bulk Editing

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

       }

   }

Thursday, March 08, 2007 1:47 PM by Miren D

# re: Real World GridView: Bulk Editing

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.

Friday, March 09, 2007 1:16 AM by Ninos Bisso

# re: Real World GridView: Bulk Editing

Luogo molto buon:) Buona fortuna!

Saturday, March 10, 2007 4:32 PM by ...

# re: Real World GridView: Bulk Editing

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

Tuesday, March 13, 2007 7:13 AM by ...

# re: Real World GridView: Bulk Editing

luogo interessante, soddisfare interessante, buon!

Thursday, March 15, 2007 5:10 PM by ...

# re: Real World GridView: Bulk Editing

Lo trovo piuttosto impressionante. Lavoro grande fatto..)

Saturday, March 17, 2007 11:40 AM by ...

# re: Real World GridView: Bulk Editing

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

Monday, March 19, 2007 2:48 AM by ...

# re: Real World GridView: Bulk Editing

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

Thanks!

Thursday, March 29, 2007 10:12 AM by Grace

# re: Real World GridView: Bulk Editing

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.

Tuesday, April 03, 2007 11:35 AM by Ginger

# add empity row at the end gridview

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

Wednesday, April 11, 2007 3:43 AM by idrees

# re: Real World GridView: Bulk Editing

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.

Friday, April 13, 2007 10:58 AM by Travis Baseflug

# re: Real World GridView: Bulk Editing

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

Tuesday, April 17, 2007 4:41 PM by Dk

# Loosing link in paging of gridview

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

Thursday, April 19, 2007 11:16 AM by Nix Roy

# Loosing link in paging of gridview

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

Thursday, April 19, 2007 11:16 AM by Nix Roy

# Where Can I download the Code

Where can I download the code for this?

Thanks,

Heather

Wednesday, April 25, 2007 1:14 AM by Heather Simpson

# re: Real World GridView: how to enter values in a gridviw at run time

sir

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

Monday, April 30, 2007 5:54 AM by dil

# Delete row missing?

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!

Tuesday, May 15, 2007 7:04 AM by Aideen

# Real World GridView: Bulk Editing for dynamic columns

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)

Wednesday, May 30, 2007 8:30 PM by Eliel

# re: Real World GridView: Bulk Editing

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.

Thursday, June 07, 2007 4:23 PM by Joe

# Suppose I want a DropDownList to initialize on a specific value?

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.

Wednesday, June 13, 2007 4:30 AM by Ruizzie

# re: Real World GridView: Bulk Editing

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

Friday, June 15, 2007 6:39 AM by sonia

# re: Real World GridView: Bulk Editing

Hi

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

Friday, June 15, 2007 7:03 AM by sonia

# re: Real World GridView: Bulk Editing

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.

Monday, June 25, 2007 3:38 PM by Sam

# BulkEditGridView: Calling Save() from DropDownList.SelectedIndexChanged()

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" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

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

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

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

       </asp:DropDownList>

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

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

           <Columns>

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

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

           </Columns>

       </cc1:BulkEditGridView>

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

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

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

           <UpdateParameters>

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

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

           </UpdateParameters>

           <SelectParameters>

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

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

           </SelectParameters>

       </asp:SqlDataSource>

   </div>

   </form>

</body>

</html>

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

{

   protected void Page_Load(object sender, EventArgs e)

   {

   }

   protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)

   {

       BulkEditGridView1.Save();

   }

}

Friday, July 13, 2007 10:08 AM by Daryl

# re: Real World GridView: Bulk Editing

Thanks a lot.. That really helped

Sunday, July 22, 2007 7:13 PM by Nabin

# re: Real World GridView: Bulk Editing

hi thanks  for this  one

but can u send  in a  vb.NET

Wednesday, July 25, 2007 6:36 AM by faizal

# Need Help Urgent

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

Monday, July 30, 2007 2:34 AM by Umit Khanna

# re: Real World GridView: Bulk Editing

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.

Friday, August 03, 2007 3:12 PM by wabster

# re: Real World GridView: Bulk Editing

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.

Friday, August 03, 2007 3:21 PM by wabster

# re: Real World GridView: Bulk Editing

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?  

Monday, August 06, 2007 1:05 PM by wabster

# Dynamically Changing the datasource for insert/update/delete

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.

Monday, August 13, 2007 12:47 AM by Prasad

# response to Monday, August 06, 2007 1:05

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

Tuesday, August 14, 2007 9:21 AM by FeGu

# Loosing row state in the grid vew on postbacks

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!

Tuesday, August 14, 2007 9:24 AM by FeGu

# re: Real World GridView: Bulk Editing

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.

Thursday, August 23, 2007 12:53 PM by Joe

# re: Real World GridView: Bulk Editing

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

           }

       }

Sunday, August 26, 2007 10:54 PM by TomD

# re: Real World GridView: Bulk Editing

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

Tuesday, September 25, 2007 12:13 PM by MichaelN

# re: Real World GridView: Bulk Editing

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

Friday, October 05, 2007 1:17 PM by Jagan

# Still post-backs, right?

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.

Monday, October 08, 2007 5:37 PM by Travich

# re: Real World GridView: Bulk Editing

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

Tuesday, October 09, 2007 5:26 PM by David Alge

# re: Real World GridView: Bulk Editing

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

Tuesday, October 16, 2007 9:04 PM by Fred

# re: Real World GridView: Bulk Editing

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.

Monday, October 22, 2007 11:16 AM by medtun.net

# re: Real World GridView: Bulk Editing

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

Thanks.

Tuesday, October 23, 2007 4:30 AM by medtun.net

# re: Real World GridView: Bulk Editing

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;

 }

}

}

Wednesday, October 31, 2007 5:41 AM by pakornss

# re: Real World GridView: Bulk Editing

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.

Wednesday, October 31, 2007 1:51 PM by DaveS

# ObjectDataSource: CompareAllValues

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?

Thursday, November 01, 2007 3:11 PM by Marco

# ObjectDataSource: CompareAllValues

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

Friday, November 02, 2007 6:38 AM by marcocuyt

# ObjectDataSource: CompareAllValues

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

Friday, November 02, 2007 6:44 AM by marcocuyt

# re: Real World GridView: Delete Record

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

Friday, November 02, 2007 11:49 AM by Burton

# re: Real World GridView: sort while editing

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?

Monday, November 05, 2007 2:17 PM by Steve

# re: Real World GridView: Bulk Editing

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

Monday, November 12, 2007 4:04 AM by Jeff

# re: Real World GridView: Bulk Editing - Inserting extra rows

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~

Monday, November 12, 2007 9:16 AM by Justin

# re: Real World GridView: DropDownField Insert Row

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.

Monday, November 12, 2007 5:51 PM by Adam

# re: Real World GridView: Bulk Editing

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

Tuesday, November 20, 2007 4:17 PM by Vaishali Rane

# re: Real World GridView: Bulk Editing

wow, thats a great control. i luv it

Saturday, November 24, 2007 7:51 AM by M.Daud

# re: Real World GridView: Bulk Editing

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.

Monday, November 26, 2007 7:16 AM by Janaka

# re: Real World GridView: Bulk Editing

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

Thursday, January 10, 2008 8:46 PM by Smurph

# re: Real World GridView: Bulk Editing

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?

Monday, January 14, 2008 3:08 PM by nutan

# re: Real World GridView: Bulk Editing

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

Tuesday, January 29, 2008 12:12 AM by Eman

# re: Real World GridView: Bulk Editing

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 ?

Tuesday, January 29, 2008 4:38 AM by Eman

# plz help me

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

Wednesday, March 05, 2008 4:01 AM by Kamesh

# re: Real World GridView: Bulk Editing

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

Monday, March 10, 2008 9:07 AM by Kythor

# re: Real World GridView: Bulk Editing

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?

Tuesday, March 18, 2008 7:18 PM by Mike

# re: Real World GridView: Bulk Editing

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

Thursday, March 27, 2008 5:46 AM by Eman

# re: Real World GridView: Bulk Editing

It's great !!!

Can I get the VB version of RealWordGrids.zip?

Thanks,

Friday, April 04, 2008 10:14 AM by HD

# re: Real World GridView: Bulk Editing

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>

Sunday, April 06, 2008 1:17 AM by HD

# re: Real World GridView: Bulk Editing

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

Wednesday, April 09, 2008 8:24 AM by Kenneth Mazur

# re: Real World GridView: ADD/INSERT ROWS

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?

Friday, May 09, 2008 12:03 PM by ep

# re: Real World GridView: Bulk Editing- Arrow Key Navigation

Matt, that's a great control.

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

handlekey is the javascript method.

       function handleKey(evt)

       {

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

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

           var str = evt.srcElement.name;

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

           var returnValue = true;

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

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

           var rowNum = parseInt(row,10);

           var colNum = parseInt(col,10);

           var newFieldName = "";

           var newTextBox = null;

           switch (evt.keyCode) {

               case 40:

                   // Down Key

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

                   break;    

               case 39:

                   // Right Key

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

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

                   returnValue = false;

               }

                   break;    

               case 38:

                   // Up Key

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

                   break;    

               case 37:

                   // Left Key

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

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

                   returnValue = false;

               }

                   break;    

           }

       newTextBox = document.getElementById(newFieldName);

       if(null != newTextBox)

           newTextBox.focus();

           return returnValue;

       }

       function formatNumberToString(number, string)

       {

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

           var strNumber = "" + number;

           while(strNumber.length < string.length){

               strNumber = "0" + strNumber;

           }

           return strNumber;

       }

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

       function currentCursorPos(el)

       {

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

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

               i=el.selectionStart;

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

               sel=document.selection;

               if(sel){

                   r2=sel.createRange();

                   rng=el.createTextRange();

                   rng.setEndPoint("EndToStart", r2);

                   i=rng.text.length;

               }

           } else {

               el.onkeyup=null;

               el.onclick=null;

           }

           return i;

       }

These functions adds the excel like navigation using arrow keys.

Sunday, May 11, 2008 11:59 PM by Mohit

# Validate for new inserted rows on save

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

Monday, May 12, 2008 8:03 AM by Fabi

# New Rows

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?

Tuesday, May 13, 2008 1:34 AM by Sita

# re: Real World GridView: Bulk Editing

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!

Tuesday, May 13, 2008 2:54 PM by Chris B

# re: Real World GridView: Bulk Editing

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.

Thursday, May 29, 2008 9:49 AM by Eric Schwartz

# re: Real World GridView: Bulk Editing

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

Wednesday, June 04, 2008 5:55 AM by Rino

# re: Real World GridView: Bulk Editing

This is nice article for refence

Monday, June 16, 2008 4:19 PM by Harshad Nayani

# re: Real World GridView: Bulk Editing

This is nice article for refence

Monday, June 16, 2008 4:19 PM by Harshad

# re: Real World GridView: Bulk Editing

Is it easy to use this GridView with a

<asp:LinqDataSource>?

Tuesday, June 17, 2008 4:50 AM by Sillion Nightfrost

# re: Real World GridView: Bulk Editing

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

Tuesday, June 17, 2008 4:24 PM by megasoft78

# re: Real World GridView: Bulk Editing

how can i set default parameters in bulkeditgridview?pls

Monday, June 23, 2008 2:24 AM by snow

# re: Real World GridView: Bulk Editing

how can i control the each cell of bulkeditgrid.

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

Monday, June 23, 2008 11:21 PM by snow

# Real World GridView: Bulk Editing

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

Sunday, July 06, 2008 8:45 AM by Shayek

# re: Real World GridView: Bulk Editing drag values

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

Monday, July 07, 2008 8:52 AM by Ritchie

# re: Real World GridView: Bulk Editing

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?

Wednesday, July 09, 2008 1:29 PM by Aaron

# Fully Editable GridView

FullyEditableGridViewinASP.NET2usingC#

Friday, July 11, 2008 5:19 AM by OnlyLiu

# if gridview has dropdownlist, how I update dropdownlist.selected value into database?

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.

Tuesday, July 22, 2008 12:24 PM by Edwin

# re: Real World GridView: Bulk Editing

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.

Thursday, July 24, 2008 11:19 AM by FrugalGuitarist.com

# re: Real World GridView: Bulk Editing

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.

Monday, August 04, 2008 1:04 PM by Rignet

# re: Real World GridView: Bulk Editing

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.

Monday, August 18, 2008 12:35 AM by rozz

# re: Real World GridView: Bulk Editing

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

Friday, August 22, 2008 2:13 PM by Eric

# re: Real World GridView: Bulk Editing

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

Wednesday, August 27, 2008 5:30 AM by Benjiman

# re: Real World GridView: Bulk Editing

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.

Tuesday, September 09, 2008 2:26 PM by Jimbo

# re: Real World GridView: Bulk Editing

Hi All,

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

Thursday, September 11, 2008 11:32 PM by anbaz

# re: Real World GridView: Bulk Editing

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

Wednesday, September 24, 2008 4:40 AM by gridview sorting

# re: Real World GridView: Bulk Editing

Hi all,

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

Friday, October 24, 2008 12:32 PM by Marco

# re: Real World GridView: Bulk Editing

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

Tuesday, November 11, 2008 8:38 PM by Jeff

# re: Real World GridView: Bulk Editing

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 !

Tuesday, December 02, 2008 6:42 AM by andré

# re: Real World GridView: Bulk Editing

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

Monday, December 08, 2008 6:29 AM by Mauro

# re: Real World GridView: Bulk Editing

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.

Friday, December 19, 2008 5:01 AM by Disha

# re: Real World GridView: Bulk Editing

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

Wednesday, January 21, 2009 5:51 PM by Wire

# re: Real World GridView: Bulk Editing

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

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

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

Friday, February 06, 2009 1:48 PM by Rebecca

# re: Real World GridView: Bulk Editing

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

Friday, February 06, 2009 2:05 PM by Rebecca

# re: Real World GridView: Bulk Editing

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

Dim trow As GridViewRow

       For Each trow In EditableGrid.Rows

           Dim rowX As Integer

           rowX = trow.RowIndex

           Dim Rgv1 As RangeValidator

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

           Rgv1.MaximumValue = Date.Today.ToShortDateString()

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

Next

Monday, February 09, 2009 3:11 PM by Rebecca

# re: Real World GridView: Bulk Editing

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

Thank you.

Tuesday, February 17, 2009 7:48 AM by I have a simple question....

# re: Real World GridView: Bulk Editing

Hi Matt,

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

Anyhow thanks for the original post, it was excellent...

Rgds, Pete...

Wednesday, March 11, 2009 8:49 AM by Pete Long

# Real World GridView: Bulk Editing-get values from editable cell

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

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

Monday, March 23, 2009 4:47 AM by Afroditi

# re: Real World GridView: Bulk Editing

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

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

It happens on the following line:

protected override void PerformSelect() {

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

Thursday, March 26, 2009 2:54 PM by Stephany

# re: Real World GridView: Bulk Editing

Hi, Matt.

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

I created CheckBoxes in my GridView, named CBSelect.

Then, I wrote this code into you function:

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

{

if (rowType == DataControlRowType.DataRow)

{

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

     && (dataSourceIndex > -1))

  {

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

    {

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

     CheckBox cbSelect = this.Rows

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

      if (cbSelect ==null)

      {

         return base.CreateRow

                    (rowIndex,dataSourceIndex,

                     rowType, rowState |

                     DataControlRowState.Edit);

      }

      else

      {

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

             (this.Rows[rowIndex].Enabled))

         {

            return base.CreateRow(rowIndex,

            dataSourceIndex, rowType, rowState

            | DataControlRowState.Edit);

         }

         else

         {

             return base.CreateRow(rowIndex,

             dataSourceIndex, rowType,

             rowState);

          }

      }

    }

  }

}

}

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

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

"There was an error rendering the control.

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

I tried everything and recieved the same result.

Could you please help me?

Thanks,

  Iris.

Monday, March 30, 2009 7:31 AM by Iris Shalev

# Real World GridView: Bulk Editing-get values from editable cell

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

You have to convert the fields into TemplateFields first.

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

Tuesday, March 31, 2009 9:46 AM by Afroditi

# re: Real World GridView: Bulk Editing

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

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

Dim Txt1 As TextBox

Dim STxt1 As String

Dim Txt2 As TextBox

Dim STxt2 As String

Dim Txt_result As TextBox

Dim pre_result As Double

Dim result As Double

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

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

STxt1 = Txt1.Text

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

STxt2 = Txt2.Text

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

result = 0.6*pre_result

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

Txt_result.Text = result.ToString

End Sub

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

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

Plzzzzzzz someone help me!!!!

Thursday, April 02, 2009 5:13 AM by Afroditi

# re: Real World GridView: Bulk Editing

I have read through the blog and the comments

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

<pages>

       <controls>

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

       </controls>

     </pages>

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

still i get the error

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

Thursday, April 16, 2009 7:38 AM by Abhishek

# re: Real World GridView: Bulk Editing

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

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

Friday, May 15, 2009 3:45 PM by Kenneth Scott

Leave a Comment

(required) 
required 
(required) 
 
Page view tracker