Adding a DropDownList to an Editable DataGrid, Part 2
By Matthew Rouse
In Part 1 we looked at the ASP.NET Web control code needed to build the DataGrid with a DropDownList used for editing data. In this part we'll examine the source code needed in the Code-behind page to make all of this work! (If you are not familiar with what Code-behind pages are and how to use them, be sure to read: ASP.NET Code Behind Pages!)
The Code-Behind
Now let's take a look at what's going on behind the WebForm. In the following code snippet, we have a
DataView object that is global to the class, as well as a method, PopulateDropDownList(),
which will fill that DataView.
|
Here, we're populating the DataSet as you normally would, except instead
of binding the DataView to anything, we're passing it off to our TempDataView object.
Remember that name? That's the same name we were using in the DataSource for the
DropDownList in our second code sample. Now when you handle the Edit event, you simply call
PopulateDropDownList, then set the index as you normally would. And Voila! You now have a
DropDownList in your DataGrid!
Okay, Great. But How Do I Retrieve The Selected Value?
This is where it gets kind of tricky. Normally if you had a DropDownList, you'd just reference
it in the Code-behind and pull the SelectedItem.Value from it. But here you can't do it! In fact,
you can't even access that control directly at all. Why not? It's defined as a control, it has a name, I referenced
it in the code-behind, what's the problem? The problem is that it's a dynamic control. It doesn't exist,
except for the exact instances when somebody is editing something. For those of you who are used to
dealing with retrieving info from textboxes in DataGrids, it's the exact same process. For those of
you who aren't, we have the following code sample:
|
In order to retrieve the value, we have to use the FindControl method inside of the
EventArgs that are passed into DataUpdate. We take the Control that
FindControl returns, and then cast it to a DropDownList.
After that, we can access everything as we normally would.
And there you go! You now have a fully functional DropDownList in your DataGrid! But remember, this
is only one of the fun features in DataGrids. Go out and explore! Try and see exactly what you can get out of
them. You'll be pleasantly surprised.
Happy Programming!




