Manually Databinding a GridView

Posted by: Aaron Goldenthal 4/19/2009 9:36 PM

One of the questions I see frequently on the ASP.NET forums is how to deal with exceptions like

The GridView 'GridView1' fired event RowEditing which wasn't handled.

The GridView 'GridView1' fired event PageIndexChanging which wasn't handled.

The GridView 'GridView1' fired event Sorting which wasn't handled.

The GridView 'GridView1' fired event RowDeleting which wasn't handled.

when manually databinding a GridView.  When I say manually databinding I mean not using a data source control specified as a DataSourceID, but rather setting the GridView’s DataSource equal to the appropriate data object and calling DataBind.  Developers who were around before ASP.NET 2.0 are familiar with how to deal with this, but since ASP.NET 2.0 most of the examples and tutorials deal with setting the DataSourceID, which buys you a lot of automation that you may not even appreciate unless you’ve done this the old fashioned way.  In this example, we’ll go through a fully featured GridView with editing, deleting, selecting, sorting, and paging functionality that is manually bound and identify the limitations and some of the workarounds.

When you use a data source control (e.g. SqlDataSource, ObjectDataSource, LinqDataSource, etc) specified in a DataSourceID, the GridView can automate many functions because, through the data source control, the GridView on its own can perform the following operations:

  • Select data (required any time databinding is required)
  • Update data
  • Delete data
  • Insert data (not necessarily applicable for a GridView, but it is for other data controls)

When you manually bind data to a GridView, the GridView itself cannot perform these operations, so they must be implemented in your code.  The GridView does know the events that should be used to implement them, so the exceptions shown above are thrown when you try to perform one of these operations, but you have implemented the appropriate event handler.

The general philosophy you’ll see here is:

  • The “-ing” event handlers (e.g. RowEditing, RowUpdating, RowDeleting, Sorting) must be implemented
  • The “-ed” event handlers (e.g. RowUpdated, RowDeleted) do not have to be implemented, and in many cases these events are never raised.

To demonstrate the details, I’ve created a very simple table ([UserID] INT, [FirstName] VARCHAR, [LastName] VARCHAR), which we’ll display with the following GridView:

   1: <asp:GridView ID="GridView1" runat="server" 
   2:     AllowSorting="true" AllowPaging="true" PageSize="5" 
   3:     AutoGenerateColumns="false" DataKeyNames="UserID" 
   4:     OnPageIndexChanged="GridView1_PageIndexChanged" 
   5:     OnPageIndexChanging="GridView1_PageIndexChanging" 
   6:     OnRowCancelingEdit="GridView1_RowCancelingEdit" 
   7:     OnRowDeleting="GridView1_RowDeleting" 
   8:     OnRowEditing="GridView1_RowEditing" 
   9:     OnRowUpdating="GridView1_RowUpdating" 
  10:     OnSorted="GridView1_Sorted"
  11:     OnSorting="GridView1_Sorting">
  12:     <Columns>
  13:         <asp:BoundField DataField="UserID" HeaderText="ID" 
  14:             SortExpression="UserID" ReadOnly="true" />
  15:         <asp:BoundField DataField="FirstName" HeaderText="First Name" 
  16:             SortExpression="FirstName" />
  17:         <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
  18:             <ItemTemplate><%# Eval("LastName")%></ItemTemplate>
  19:             <EditItemTemplate>
  20:                 <asp:TextBox ID="LastNameTB" runat="server" 
  21:                     Text='<%# Bind("LastName") %>'></asp:TextBox>
  22:             </EditItemTemplate>
  23:         </asp:TemplateField>
  24:         <asp:CommandField HeaderText="Actions" ShowDeleteButton="true" 
  25:             ShowEditButton="true" ShowSelectButton="true" />
  26:     </Columns>
  27:     <AlternatingRowStyle CssClass="alt" />
  28:     <SelectedRowStyle CssClass="selected" />
  29:     <PagerStyle CssClass="pager" />
  30:     <PagerSettings Mode="NextPrevious" NextPageText="Next >" 
  31:         PreviousPageText="< Prev" />
  32: </asp:GridView>

As you can see this GridView is fairly straightforward:

  • 2 BoundFields
  • 1 TemplateField with a template for display and editing (to show the difference later in retrieving data from a BoundField and a TemplateField)
  • 1 CommandField with the appropriate buttons shown
  • Paging allowed
  • Sorting allowed
  • DataKeyNames set to save the UserID

This is the final GridView markup, so you can see the event handlers we’re going to implement.  We’ll start with binding data to the GridView, then build up functionality from there.

Databinding the GridView

First, we’ll implement a method to databind the GridView, which will be called whenever databinding needs to be performed.

   1: protected void BindData()
   2: {
   3:     DataClassesDataContext context = new DataClassesDataContext();
   4:     var users = from u in context.Users
   5:                 select u;
   6:     GridView1.DataSource = users.ToList();
   7:     GridView1.DataBind();
   8: }

We’re using Linq to SQL to pull data from our database and bind it to the GridView.  We’ll revisit this method when we implement the sorting functionality.

We also need force databinding to occur when then page is loaded, which we’ll handle in Page_Load.

   1: protected void Page_Load(object sender, EventArgs e)
   2: {
   3:     if (!Page.IsPostBack)
   4:     {
   5:         BindData();
   6:     }
   7: }

Paging the GridView

Any time the page index is changed, the GridView must be databound, so we need to handle the appropriate event, which in this case is PageIndexChanging.

   1: protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
   2: {
   3:     GridView1.PageIndex = e.NewPageIndex;
   4:  
   5:     GridView1.EditIndex = -1;
   6:     GridView1.SelectedIndex = -1;
   7: }

The required actions for paging to work are setting the new page index, setting the DataSource, and calling DataBind (the last two through the BindData method).  In addition to that, we’re resetting the EditIndex and SelectedIndex when the page is changed to avoid cases, for example, where you change pages and are suddenly editing a different item.  BindData could be called in PageIndexChanging, but to show that it the event is raised, we’ve handled that in PageIndexChanged.

   1: protected void GridView1_PageIndexChanged(object sender, EventArgs e)
   2: {
   3:     BindData();
   4: }

The important point is not which of these two events call BindData, but one of them must or the GridView will not be updated.

Sorting the GridView

Sorting is a little more complicated than paging.  When bound using a DataSourceID, the GridView internally tracks the current SortExpression and SortDirection, and those are available through properties with the same names.  When you manually bind the GridView, this tracking does not occur, so we must implement some mechanism for tracking those values.  We also want it to be something persistent, so that, for example, if you sort, then page, the sort is maintained.  The way we’ll accomplish this is to create two properties that store those values in ViewState.

   1: protected string SortExpression
   2: {
   3:     get
   4:     {
   5:         return ViewState["SortExpression"] as string;
   6:     }
   7:     set
   8:     {
   9:         ViewState["SortExpression"] = value;
  10:     }
  11: }
  12:  
  13: protected SortDirection SortDirection
  14: {
  15:     get
  16:     {
  17:         object o = ViewState["SortDirection"];
  18:         if (o == null)
  19:             return SortDirection.Ascending;
  20:         else
  21:             return (SortDirection)o;
  22:     }
  23:     set
  24:     {
  25:         ViewState["SortDirection"] = value;
  26:     }
  27: }

We’ll get to how these properties are populated shortly, but first we need to go back to the BindData method.  The original method shown above did not implement any sorting, but now that we have a place to store the SortExpression and SortDirection we need to change that.

   1: protected void BindData()
   2: {
   3:     DataClassesDataContext context = new DataClassesDataContext();
   4:     var users = from u in context.Users
   5:                 select u;
   6:  
   7:     bool sortAscending = 
   8:         this.SortDirection == SortDirection.Ascending ? true : false;
   9:  
  10:     switch (this.SortExpression)
  11:     {
  12:         case "FirstName":
  13:             users = sortAscending ? users.OrderBy(u => u.FirstName) : 
  14:                 users.OrderByDescending(u => u.FirstName);
  15:             break;
  16:         case "LastName":
  17:             users = sortAscending ? users.OrderBy(u => u.LastName) : 
  18:                 users.OrderByDescending(u => u.LastName);
  19:             break;
  20:         default:
  21:             users = sortAscending ? users.OrderBy(u => u.UserID) : 
  22:                 users.OrderByDescending(u => u.UserID);
  23:             break;
  24:     }
  25:     GridView1.DataSource = users.ToList();
  26:     GridView1.DataBind();
  27: }

After specifying the query, we add the appropriate sorting.  We can implement it in this way without a performance impact because the data is not actually retrieved from the database until required, so we can build up a chain of queries up to that point and only the end result will be pulled from the database.  We’re sorting on the appropriate field based on the SortExpression, and setting the direction based on SortDirection by calling either the OrderBy or OrderByDescending methods.

Finally we need to populate the SortExpression and SortDirection when they change, and we’ll handle that in the Sorting event.

   1: protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
   2: {
   3:     if (this.SortExpression == e.SortExpression)
   4:     {
   5:         this.SortDirection = this.SortDirection == SortDirection.Ascending ?
   6:             SortDirection.Descending : SortDirection.Ascending;
   7:     }
   8:     else
   9:     {
  10:         this.SortDirection = SortDirection.Ascending;
  11:     }
  12:     this.SortExpression = e.SortExpression;
  13:  
  14:     GridView1.EditIndex = -1;
  15:     GridView1.SelectedIndex = -1;
  16: }

The new sort expression is available through e.SortExpression based on the user’s selection.  There is a sort direction available through e.SortDirection.  When you bind a GridView through a DataSourceID, the GridView will update this value since it is internally tracking the sort expression, so it knows when to switch between ascending and descending.  When manually databinding the GridView, this will always show ascending, so we need to handle this manually with the following logic:

  • If the SortExpression has not changed, reverse the SortDirection (switching between ascending and descending)
  • If the SortExpression has changed, the SortDirection is ascending

After that we save the new SortExpression.  As with paging, we also reset the EditIndex and SelectedIndex when sorting.  Also like paging, so show that it does get called, databinding is handled in the Sorted Event (honestly, we will get to some “-ed” events that are not raised).

   1: protected void GridView1_Sorted(object sender, EventArgs e)
   2: {
   3:     BindData();
   4: }

Editing Records in the GridView

For editing there are events that need to be handled: entering edit mode, cancelling out of edit mode, and updating from edit mode.  First, we’ll handle entering edit mode:

   1: protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
   2: {
   3:     GridView1.EditIndex = e.NewEditIndex;
   4:     BindData();
   5: }

This is the minimum we need to do to enter edit mode: set the new EditIndex and call BindData (which sets the GridView’s DataSource and calls DataBind).

Cancelling out of edit mode is very similar.

   1: protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
   2: {
   3:     GridView1.EditIndex = -1;
   4:     BindData();
   5: }

Finally, we’ll handle the RowUpdating method to save the new values.  Most of the automation that’s provided by the GridView when bound using a DataSourceID is lost when manually databinding:

  • The original values are not available through e.OldValues. 
  • The new values are not available through e.NewValues.
  • The DataKeys for the affected row are not available through e.Keys

Basically, all the GridView does for you is pass the EditItemIndex through e.RowIndex and dealing with everything else is up to you.

   1: protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
   2: {
   3:     // e.Keys, e.NewValues, and e.OldValues are only populated if using DataSourceID    
   4:     int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
   5:  
   6:     DataClassesDataContext context = new DataClassesDataContext();
   7:     var user = (from u in context.Users
   8:                 where u.UserID == id
   9:                 select u).Single();
  10:  
  11:     TextBox firstNameTB = GridView1.Rows[e.RowIndex].Cells[1].Controls[0] as TextBox;
  12:     user.FirstName = firstNameTB.Text;
  13:  
  14:     TextBox LastNameTB = GridView1.Rows[e.RowIndex].FindControl("LastNameTB") as TextBox;
  15:     user.LastName = LastNameTB.Text;
  16:  
  17:     context.SubmitChanges();
  18:  
  19:     GridView1.EditIndex = -1;
  20:     BindData();
  21: }

First, we obtain the UserID of the affected row from the GridView DataKeys collection, which we use to pull the appropriate record from the database.  At that point we need to get the new values so we can update the record, which is done slightly differently for the BoundField and the TemplateField. 

For the BoundField, we don’t know the ID of the TextBox since it’s autogenerated by the BoundField, so we obtain a reference to it by getting the first control in the appropriate cell in the edited row.  Since it’s a BoundField, the TextBox is going to be Control[0]. Once we have a reference to the TextBox, we set the new first name.

For the TemplateField, we do know the ID of the control since we specified it in the markup, so we obtain a reference to it by calling FindControl on the appropriate row of the GridView.  The GridViewRow is the naming container for the TextBox in this case, so we need to call FindControl on the appropriate row, but we do not need to call it on the specific cell.  Once we have a reference to the TextBox, we set the new last name and save the changes (through the SubmitChanges method).

Once the changes are saved, we need to do a little clean up on the GridView.  We reset the EditIndex, and we must again call BindData.  You’ll note we did not accomplish any of this in the RowUpdated event because that event is never fired when manually databinding to a GridView.

Deleting Records in the GridView

As with updating, most of the automation that’s provided by the GridView when bound using a DataSourceID is lost when manually databinding:

  • The original values are not available through e.Values.
  • The DataKeys for the affected row are not available through e.Keys

Basically, all the GridView does for you is pass the RowIndex of the row to delete through e.RowIndex and dealing with everything else is up to you, so it’s very similar to updating.

   1: protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
   2: {
   3:     // e.Keys and e.Values are only populated if using DataSourceID
   4:     int id = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
   5:     DataClassesDataContext context = new DataClassesDataContext();
   6:     var user = (from u in context.Users
   7:                 where u.UserID == id
   8:                 select u).Single();
   9:     context.Users.DeleteOnSubmit(user);
  10:     context.SubmitChanges();
  11:  
  12:     BindData();
  13: }

First, we obtain the UserID of the affected row from the GridView DataKeys collection, which we use to pull the appropriate record from the database.  We then delete the record, and call BindData.  As with updating, none of this is handled in the RowDeleted event because that event is never fired when manually databinding to a GridView.

Selecting Records in the GridView

Selecting is actually the easiest of all of these to implement, all you have to do is – nothing.  Selecting will work without any code.  The reason is that selecting in a GridView does not cause a databind, it simply changes styles related to the selected row. 

Note this behavior is not the same for the ListView.  Since the ListView can have a separate template for the selected item, and this may contain different data, the ListView does perform a databind when changing the selected index.

Summary

This article has detailed the type of code that must be written when manually databinding a GridView with paging, sorting, editing, deleting, and selecting capability.

Download sample website: GridViewManualDataBinding_2_0.zip (243 kb)

Updated April 26, 2009: Example updated to change one of the BoundFields to a TemplateField to the show the differences in retrieving data between the two types of fields.

Updated May 11, 2009: Added VB.NET example.

Tags: ,
Categories: Data Controls
E-mail | Kick it! | DZone it! | del.icio.us Permalink | Comments (37) | Post RSSRSS comment feed

Comments (37) -


Indonesia Aldy 
5/17/2009 11:36 AM
Aldy

hi,

how about in vb code? can u show me ?

thanks.


5/21/2009 12:16 AM
Aaron
Hi Aldy,

In general, you can use a converter like www.developerfusion.com/.../ to convert C# to VB, but I have updated the example download with the VB.NET code.


United States Aldy 
5/21/2009 12:25 AM
Aldy


Hi Aaron,

i cannot extract your zip file... any idea ?


United States Aldy 
5/21/2009 12:29 AM
Aldy

Hi Aaron,

Thank U Very much ....


Hungary dargzero 
5/21/2009 5:40 AM
dargzero
Excellent guide


5/21/2009 6:47 AM
Aaron
Sorry Aldy, try the download now.  I forgot to change the compression type.


Australia john 
6/11/2009 4:29 AM
john
Hi Aaron, Do you know how to add Formview from you code. For example, if I select one of the row from Gridview, then Formview will show the detail?

Thank you


6/17/2009 3:18 PM
Aaron
Hi john,

I haven't specifically done that where everything was manually bound, but in general I'd do something like this:
1. Implement event handlers/methods similar to those above for the FormView (if not using a data source control).
2. Add a GridView SelectedIndexChanged handler and in that handler call the method to bind the FormView (or call FormView.DataBind if using a data source control).
3. For any of the FormView's "-ed" methods where data could have changed (e.g. ItemUpdated, ItemDeleted), re-bind the GridView.

Aaron


United States joejoe 
6/27/2009 12:00 AM
joejoe
This is exactly what I've been looking for upwards of 3 hours! Very hard to find a post any more in regards to manual database binding.  Good work


India amit kumar thakur 
7/15/2009 8:57 PM
amit kumar thakur
i want to call two different function on page index change event of grid view but the fn are not working properly
mail  me on
thakur_amit15@rediffmail.com

code is:
gv.pagechange_index
{
gv.pageindex=e.newpageindex;
//bindfn1();
//bindfn2();
if(status==1)
{
bindfn1();
}
if(status==0)
{
bindfn2();
}

i have called fn1 on buttun 1 and set  statua=1;
and fn2 on button 2 and int status=0;


so when the button click status change


but after page  data is not coming what should come

help me out


8/18/2009 12:51 AM
Aaron
Charles - I appreciate the offer, but my life's a little too busy at this point to take that on (as you can probably tell by how long it's been since I posted anything here).

Amit Kumar Thakur - Hopefully you got your problem solved, but in case you haven't, I'll take a shot.  Without seeing all of the code, my guess is that the status value is not being persisted.  Here's a good article with options for persisting state: msdn.microsoft.com/en-us/magazine/cc300437.aspx.

Aaron


United States Lee Zeitz 
8/29/2009 6:19 AM
Lee Zeitz
Hi - I have a problem where the DataKeys are set for the first page and I cannot seem to set them again.  When I page, the gridview shows the correct data, but the DataKeys remain set to the data from page 1.  Any ideas?

BTW - This was one of the most informative posts I have seen in some time.

Thanks,

Lee


United States Ryan Andres 
4/4/2010 11:04 PM
Ryan Andres
Very awesome post. Couldn't be any easier even with all that information!


Canada David 
7/9/2010 4:44 PM
David
Thank you for this post!  I had no clue what to do but after reading this it's so clear


United States sonet 
7/17/2010 12:46 PM
sonet
First of all, thanks for this  article. Secondly, what is the best way to approach asp.net?  I have to admit, i do not program in asp.net on a daily basis but whenever i am away from it (even a month or so) i keep on forgetting the logics behind the control?  It is like i have to reeducate my self all over again. Also these so called (no programming needing controls) do not behave well with large amount of data, and combine with view states all that the page size is kinda bloated.

Let's say i do not have visual studio for a second, how do i remember things such as "GridView1.EditIndex = e.NewEditIndex;" when and where to call it?  it is just not really intuitive...  

Just give me an idea, Anybody? I am frustrated.



United States Michael 
8/5/2010 12:24 AM
Michael
Thank you for the great post!


Netherlands Rik 
8/6/2010 8:08 AM
Rik
Wow thx !!
I was also looking for this for a couple of hours and now everything works perfect.

Keep up the good work.


Japan Mark 
8/9/2010 5:09 AM
Mark
I've spent the last few days wrestling with Mono trying to get GridView working properly.  Displaying data is the easy part; updating data, not so easy.  Mono claims to have LinqDataSource support, but it's not complete so editing and deleting don't work at all (error 500: Not implemented).  That left me with doing things manually and information on that is sparse.  Your post solved all of my problems.  Thank you!


8/17/2010 8:40 AM
Guy
Great Example. However, I can not get the RowUpdating Event to work. When the event is called the the gridview does not have rows. the gv.rows.count = 0 and I get an index out of range on this line:

Dim tbDegree As TextBox = TryCast(gvAcademic.Rows(e.RowIndex).FindControl("txtDegree"), TextBox)

e.RowIndex has a value of 1.

Here is my event:

    Protected Sub gvAcademic_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs) Handles gvAcademic.RowUpdating

        Dim id As Integer = Int32.Parse(gvAcademic.DataKeys(e.RowIndex).Value.ToString())

        Dim tbDegree As TextBox = TryCast(gvAcademic.Rows(e.RowIndex).FindControl("txtDegree"), TextBox)

        gvAcademic.EditIndex = -1

        gvAcademic.DataSource = GetDataSource()
        gvAcademic.DataBind()

    End Sub

Any help would be appreciated.


8/17/2010 8:59 PM
Aaron
@Guy,

That sounds like what you'd see if ViewState was disabled for the GridView.  If that's the case, try databinding on every page load, not just on postback.  This is yet another case where data source controls are helping you behind the scenes - if ViewState is disabled then the GridView will be databound as the post data is being processed (which needs to be done to re-populate the original data in the GridView, data that's otherwise stored in ViewState).

Aaron


Sweden Fred 
9/10/2010 7:30 AM
Fred
Just wanted to say "THANK YOU" !!!

I use Linq to execute a SPROC to search according to wildcard filters and the "Where.Contains" is not as good as "TSQL LIKE" as it a forces you to use both pre & post wildcards. But I had huge problems with edit + sorting and your tutorial saved my day:


Sweden Fred 
9/16/2010 8:10 AM
Fred
I found an even better solution here: msdn.microsoft.com/.../...rols.linqdatasource.aspx

The "Selecting" event on the LinqDataSource is fired when the data is fetched, here you can override what result is return to the LinqDataSource. This way you can still keep the GridView bound to the LinqDataSource and do not need to manualy implement sorting etc.


United States Jason Klotz 
3/3/2011 11:07 AM
Jason Klotz
Great article.  If only the MSDN were as useful.


United States  dan 
4/27/2011 10:03 AM
 dan
This is great. Just what I needed. Microsoft documentation is bad.


United States Jason 
5/18/2011 11:56 AM
Jason
Thanks so much, this is great!

I know this is an old post but if there is anyway I might be able to implement alphabet paging in place of the "next / previous" I really need that for my project.

Any ideas?


India jayesh goyani 
6/16/2011 1:07 PM
jayesh goyani
great article with example...


Israel Dov 
6/20/2011 8:14 AM
Dov
This article was very helpful for me for paging of grid view. However I still have a problem that paging only works after clicking twice.


India Muralidhara 
8/5/2011 11:06 AM
Muralidhara
Thank you so much .this article helped me a lot .it has clear demonstration.
great workSmile


South Africa mr e 
9/23/2011 1:56 PM
mr e
hi am having problems edit on the gridview please help me


India Jayantha 
10/12/2011 11:12 AM
Jayantha
Good Article..
After 2 day searched in internet i found one good article..
Sexy sharing..Good work Excellent...

can you pls upload repeater control guide..(I need it)


India Nibedita 
11/18/2011 6:15 AM
Nibedita
In gridview, i am binding data from database but when i am exicuting the application, the data of gridview coming out of the page. Can u please help me.


Indonesia igan 
11/29/2011 2:49 AM
igan
Excellent post, this is what i'm looking for, works like a charm


1/5/2012 3:59 PM
Adam Edell
Great post!

@Aaron: regarding your correct comment to @Guy, the problem is that when you DataBind() on every PostBack (which is a solution to the problem of when you turn off ViewState) you end up making two database calls on every Page_Load! This has always annoyed me, so I came up with a solution to the double-query problem that has plagued me for years when working with ViewState off:

adamonsoftware.blogspot.com/.../...wstate-off.html

Let me know if this is helpful to anyone!


India laxman 
4/24/2012 5:23 AM
laxman
good article


United States Bruno Aun 
5/7/2012 2:32 PM
Bruno Aun
Worked indeed... LIFE SAVER bro!!

thanks for sharing


India Jagdeep Singh Mankotia 
6/7/2012 4:20 AM
Jagdeep Singh Mankotia
Below code is working fine for me:


.aspx
<EditItemTemplate>
  <aspLaughingropDownList ID="ddlCompanyList" runat="server" AppendDataBoundItems="true"/>
  <asp:HiddenField ID="hdnCompanyID" Value='<%# Eval("CompnayDetails.ID") %>' runat="server" />
</EditItemTemplate>


.cs
protected void GridViewUser_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewUser.EditIndex = e.NewEditIndex;
            LoadUserList();


//Get the list of Company with ID from BLL
            var dSource = CompanyDetails.GetActiveCompanyList();

//Find the DropDown Control in Grid view
            DropDownList ddl = (DropDownList)(GridViewUser.Rows[GridViewUser.EditIndex].FindControl("ddlCompanyList"));

//Chek if Control found in gridview
            if (ddl != null)
            {
                ddl.DataTextField = "Name";
                ddl.DataValueField = "ID";
                ddl.DataSource = dSource;
                ddl.DataBind();
            }
//Find the Hidden filed in Gridview
            HiddenField hdnID = new HiddenField();
            hdnID = (HiddenField)GridViewUser.Rows[GridViewUser.EditIndex].FindControl("hdnCompanyID");          

//Set the selected value of dropdown list with compare to Hidden field
            ddl.SelectedValue = hdnID.Value.ToString();
        }
// Jagdeep Mankotia


France assurance auto 
6/16/2012 3:54 AM
assurance auto
You right!! Think exactly the same