Click here to Skip to main content
Click here to Skip to main content
Go to top

Creating an ASP.NET GridView Custom Field of type DropDownList

, 30 Nov 2008
Rate this:
Please Sign up or sign in to vote.
Sometimes you need to use a DropDownList in a GridView in a way to see the text of the field and save the value to the database. Here we extended the “BoundField” class, and add features to create a column type of “DropDownList”.

Introduction

Sometimes, you need to use a DropDownList in a GridView in a way to see the text of fields and save values in to your database. Here, we have extended the “BoundField” class and added features to create a column type of “DropDownList”.

For example, in this picture, you can see two tables, Customer and Category.

Suppose you need to edit the content of the Customer table with a GridView and select “Customer Category” through a “DropDownList”. You want to see the CategoryName in the grid but save CategoryID in to the database, like in this picture:

GridEdit.jpg

Background

You have two solutions:

  • The first solution is to create a Template column of type DropDownList.
  • The second solution is to create a new column type with the “DropDownList” editor and introduce an “Entity Name” for it. Here, we have extended the “BoundField” class and added features to create a column type of “DropDownList”.

Using the code

Now, you can use this column type easily, like:

<CustomFields:ComboBoxField BusinessObjectName="CategoryBO" 
   DataTextField="CategoryName" DataValueField="CategoryID" 
   SelectMethod="GetCategories" DataField="Category" 
   IDDataField="CategoryID" SortExpression="Category" 
   HeaderText="Category"></CustomFields:ComboBoxField>

For this reason, you should join the main table with the referenced table and create a view containing both the text and the value of the combobox field:

CREATE VIEW vCustomers AS
SELECT   dbo.Customers.CustomerID, dbo.Customers.FirstName, dbo.Customers.LastName, 
         dbo.Customers.CategoryID, dbo.Category.CategoryName AS Category FROM

         dbo.Customers INNER JOIN
         dbo.Category ON dbo.Customers.CategoryID = dbo.Category.CategoryID

And, create both text and value columns in the GridView and set the value column “visiblity” to False:

<CustomFields:ComboBoxField BusinessObjectName="CategoryBO" 
   DataTextField="CategoryName" DataValueField="CategoryID" 
   SelectMethod="GetCategories" DataField="Category"
   IDDataField="CategoryID" SortExpression="Category" 
   HeaderText="Category"></CustomFields:ComboBoxField>

<asp:BoundField DataField="CategoryID"
   HeaderText="CategoryID"
   SortExpression="CategoryID"
   Visible="False"/>

The first step is to create a new class inherited from the BoundField class:

public class ComboBoxField:BoundField
{
    . . .

The second step is to change the ExtractValuesFromCell method to get the DropDownList control for editing the cell in edit mode:

public override void ExtractValuesFromCell(IOrderedDictionary dictionary, 
       DataControlFieldCell cell, DataControlRowState rowState, bool includeReadOnly)
{
    . . . .
    if (cell.Controls.Count > 0)
    {

        // Get column editor of type DropDownList of current cell 
        control = cell.Controls[0];
        DropDownList box = control as DropDownList;
        if ((box != null) && (includeReadOnly || box.Enabled))
        {
            obj2 = box.Text;
            if (obj2 != null)
            {

                // extract value from DropDownList
                ListItem itm = box.Items.FindByValue(obj2.ToString());
                obj3 = itm.Text;
            }

        }
    }
    if (obj2 != null)
    {
        if (dictionary.Contains(dataField))
        {
            dictionary[dataField] = obj2;
        }
        else
        {
            //put both text and value into the dictionary
            dictionary.Add(dataField, obj3);
            dictionary.Add(this.IDDataField, obj2);

The third step is changing the InitializeDataCell method to create the DropDownList control in the editing cell.

protected override void InitializeDataCell(DataControlFieldCell cell, 
                   DataControlRowState rowState)
{
    Control child = null;
    Control control2 = null;
    if ((((rowState & DataControlRowState.Edit) != DataControlRowState.Normal) && 
           !this.ReadOnly) || ((rowState & DataControlRowState.Insert) 
           != DataControlRowState.Normal))
    {
        // If data cell is in edit mode, create DropDownList editor for this cell
        // and set data properties.
        DropDownList box = new DropDownList();
        box.DataSource =this.GetDataSource();
        box.DataMember = this.BusinessObjectName;
        box.DataTextField = this.DataTextField;
        box.DataValueField = this.DataValueField;
        box.DataBind();
        
        .
        .
        .


protected override void OnDataBindField(object sender, EventArgs e)
{
    Control control = (Control)sender;
    Control namingContainer = control.NamingContainer;
    object dataValue = this.GetValue(namingContainer);
    bool encode = (this.SupportsHtmlEncode && this.HtmlEncode) && (control is TableCell);
    string str = this.FormatDataValue(dataValue, encode);
    if (control is TableCell)
    {
        if (str.Length == 0)
        {
            str = " ";
        }
        ((TableCell)control).Text = str;
    }
    else
    {
        //If data cell is in edit mode, set selected value of DropDownList 
        if (dataValue != null)
        {

            ListItem itm = ((DropDownList)control).Items.FindByText(dataValue.ToString());
            ((DropDownList)control).Text = itm.Value;
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Javad Zarrinabadi

Iran (Islamic Republic Of) Iran (Islamic Republic Of)
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmembermohse9018-Sep-13 6:41 
GeneralMy vote of 5 Pinmembermeltamps1-Sep-13 23:42 
QuestionVB version o this code Pinmemberbaijuep197026-Sep-12 15:37 
GeneralThk PinmemberMember 195878412-Sep-12 5:34 
Generalinsert new person Pinmemberrasmus471115-Nov-10 2:18 
GeneralThat's great! Pinmemberpappe8210-Feb-10 0:12 
Generalproblem for using five dropdownlist with data in gridview Pinmembersahil4dotnet0930-May-09 2:05 
Hi, Anyone can tellme how can i use four or five dropdown list when i select any item from the drop down list then data will come in the gridview, i want these dropdown list behaving like in gridview as header template.for example:-
If i have one dropdownlist1 and i allrady selected items for example:-
else if (DropDownList1.Items[2].Selected)
{
da = new SqlDataAdapter("Select Customer_Name FROM PRI", "data source=.;uid=sa;pwd=sa;database=sunny;integrated security=true;");
}
and i m also binding the data as:-
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
so when i m selecting one dropdown list it's working but when i m selecting two or more drop down list then it will show the data only for that dropdownlist which i m selecting.not others dropdownlist data in gridview.....so anyone can tellme how can i done this one.
 

Thank's
Sahil
GeneralPost Pinmemberrklundt2-Dec-08 1:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140922.1 | Last Updated 30 Nov 2008
Article Copyright 2008 by Javad Zarrinabadi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid