Click here to Skip to main content
15,867,704 members
Articles / Web Development / ASP.NET
Article

Creating an ASP.NET GridView Custom Field of type DropDownList

Rate me:
Please Sign up or sign in to vote.
4.19/5 (18 votes)
30 Nov 2008CPOL1 min read 102K   2.2K   28   13
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.

Image 1

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:

XML
<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:

SQL
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:

XML
<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:

C#
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:

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

C#
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)


Written By
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionJavad, u are awesome developer. Pin
Member 1267949811-Aug-16 2:56
Member 1267949811-Aug-16 2:56 
Questionhi Pin
hami6322-Jun-15 1:08
hami6322-Jun-15 1:08 
AnswerRe: hi Pin
hami6322-Jun-15 1:13
hami6322-Jun-15 1:13 
Generalفوق العاده بود Pin
Hadi Zaker13-Oct-14 10:40
Hadi Zaker13-Oct-14 10:40 
GeneralMy vote of 5 Pin
mohse9018-Sep-13 6:41
mohse9018-Sep-13 6:41 
GeneralMy vote of 5 Pin
meltamps1-Sep-13 23:42
meltamps1-Sep-13 23:42 
QuestionVB version o this code Pin
baijuep197026-Sep-12 15:37
baijuep197026-Sep-12 15:37 
GeneralThk Pin
Member 195878412-Sep-12 5:34
Member 195878412-Sep-12 5:34 
Generalinsert new person Pin
rasmus471115-Nov-10 2:18
rasmus471115-Nov-10 2:18 
GeneralThat's great! Pin
pappe8210-Feb-10 0:12
pappe8210-Feb-10 0:12 
Generalproblem for using five dropdownlist with data in gridview Pin
sahil4dotnet0930-May-09 2:05
sahil4dotnet0930-May-09 2:05 
GeneralPost Pin
SGnK2-Dec-08 1:54
SGnK2-Dec-08 1:54 

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

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