Wednesday, November 08, 2006

DropDownList in GridView


The problem I encountered was being able to use an updateable GridView using data from multiple tables. The two main tables are called Category and Forum. A forum can only belong to one category, but a category can contain multiple forums. To make things a bit more difficult, I used a associative table to relate the two called CategoryForum.

My goal is to be able to manage my forums without have to know the category ID of each category. It should be simple enough for a novice to use. My architectural solution had several components. Of course, I had the GridView. Then I had two ObjectDataSources using a web service to return forum and category data. The forum data includes a category ID via an INNER JOIN in the query. The category data is just the list of all categories.

First, I override the Page's OnInitComplete method to capture the update event:



   1:  protected override void OnInitComplete(EventArgs e)

   2:  {

   3:    base.OnInitComplete(e);

   4:    gridView.RowUpdating +=

   5:      new GridViewUpdateEventHandler(gridView_RowUpdating);

   6:  }


Next, I wrote some code for the overridden method. This code will store my DropDownList's data in the updating data objects field:

void gridView_RowUpdating(Object sender, GridViewUpdateEventArgs e) {
int index = gridView.EditIndex;
GridViewRow row = gridView.Rows[index];
DropDownList categoryDropDown =
(DropDownList) row.FindControl("ddlCategoryName");
e.NewValues["CategoryId"] =
int.Parse(categoryDropDown.SelectedValue);
}

That's all the code-behind code I needed. In design view I have two ObjectDataSources wired up to a web service that simply delivers a DataSet to each. One DataSet is my Forum data, and the other is Category data. Here's the EditItemTemplate code for the DropDownList. The datasource for the GridView is the ForumData. I used the Category datasource for the DropDownList.

<asp:TemplateField HeaderText="Category" SortExpression="CategoryName">
<ItemTemplate>
<%# Eval("CategoryName") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList runat="server"
ID="ddlCategoryName" DataTextField="CategoryName"
DataValueField="CategoryId" DataSourceID="objCategories" />
</EditItemTemplate>
</asp:TemplateField>

No comments:

Post a Comment