WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 175 users


WorldofASP.NET >> ASP.NET >> Unedited ASP.NET

Adding DropDownList in Datagrid Editable Area

Returning DataTable type to Dropdownlist in Editable DataGrid
Published Date : 10 Aug 2008
Author : Hans Candra
Language : C#
Platform : .NET
Technology : Web Forms
Views : 1803
Rating : (0 votes so far)



Introduction

More and more developers are finding out just how useful DataGrids are, but there is so much involved in this unique and powerful tool, that hardly anybody knows exactly what it's capable of. For instance, most people know that you can edit items in-place with a DataGrid, but few know that you can select the type of control that you want to use for the editing. Instead of using the default TextBox that it gives you, you can choose to use a DropDownList, RadioButtonList or any other bindable control. In this article, I will explain how to select multiple DropDownList values when the DropDownList is one of the columns of the DataGrid.

Main

The data choices for some database table columns are relatively fixed. Examples would be countries, states, and age group for instance. In these cases a dropdown list of fixed choices makes more sense than keyboard input where mistakes can be made easily. In an editable datagrid you can include dropdownlistboxes, although they must be populated at run time. You cannot do it at design time. In order to accomodate the dropdownlistbox the datagrid must use TemplateColumns with ItemTemplates.

An ASP.NET DataGrid for example:

<asp:DataGrid id=dgEmployee OnItemCommand="dgEmployee_ItemCommand" Width="100%" 
OnItemDataBound="dgEmployee_ItemDataBound" AutoGenerateColumns="false" runat="server">
                        <COLUMNS>
<asp:BoundColumn Visible="false" HeaderStyle-Width="18%" ReadOnly="true" 
HeaderText="Employee ID" DataField="EmployeeID"></asp:BoundColumn>
                            <asp:TemplateColumn HeaderText="Age Group" ItemStyle-Width="14%">
                                <ITEMTEMPLATE>
                                    <asp:Label id="lblAgeGroup" runat="server" Text='
<%#DataBinder.Eval(Container.DataItem,"AgeGroup") %>'></asp:Label>
                                </ITEMTEMPLATE>
                                <EDITITEMTEMPLATE>
                                    <asp:DropDownList id="ddlAgeGroup" runat="server" 
DataValueField="AgeGroupID" 
DataTextField="AgeGroup" DataSource="<%# GetAgeGroup() %>">
                                    </asp:DropDownList>
                                </EDITITEMTEMPLATE>
                            </asp:TemplateColumn>
                      </COLUMNS>
</asp:DataGrid>

In the first DataBound Employee ID method. We only bound the retrived data to a DataGrid first column. The Second method is main point what I want to show here. With ItemTemplate in DataGrid you can show the data retrieved and also edit the data onTable without any form, just click a single button and all record in a row can be editable. Here I mean when a user goes to edit, the system will supply them with a textbox for editing, with no help needed from you. For most cases, this is all you need. But what about the cases where you want them to be able to select from a DropDownList when they're editing?

For this, we use ItemTemplates. Instead of the BoundColumn in the first code method, we'll use the TemplateColumn to define exactly how to handle the data. In the code above, you've noticed that the TemplateColumn is divided into two parts: an ItemTemplate, and an EditItemTemplate. This allows us to define things for both the display mode, as well as when it's in edit mode.

Next you will also need to insert an Edit Button, Update Button, and Cancel Update Button on last column on DgEmployee DataGrid Above.

<asp:TemplateColumn HeaderStyle-Width="12%" HeaderText="Action">
                                <ITEMTEMPLATE>
                                    <asp:Button id="btnEditEmployee" runat="server" 
Text="Edit" CommandArgument='

<%#DataBinder.Eval(Container.DataItem,"EmployeeID") %>' 
CommandName="EditEmployee"></asp:Button>
                                </ITEMTEMPLATE>
                                <EDITITEMTEMPLATE>
                                    <asp:Button id="btnUpdateEmployee" runat="server" 
Text="Update" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"EmployeeID") %>' 
CommandName="UpdateEmployee"></asp:Button>
                                    <asp:Button id="btnCancelEmployee" runat="server" 
Text="Cancel" CommandArgument='<%#DataBinder.Eval(Container.DataItem,"EmployeeID") %>' 
CommandName="CancelEmployee"></asp:Button>
                                </EDITITEMTEMPLATE>
</asp:TemplateColumn>

Now we will look at the backend C# code. First is a method to retrieve ddlAgeGroup dropDownList DataFieldText and DataFieldValue:

    protected DataTable GetAgeGroup()
    {
        DataSet ds = new DataSet();
        ds.Tables.Add();
        ds.Tables[0].Columns.Add("AgeGroup");
        ds.Tables[0].Columns.Add("AgeGroupID");

            DataRow dr = ds.Tables[0].NewRow();
            dr["AgeGroup"] = "0-12";
            dr["AgeGroupID"] = "Child";
            ds.Tables[0].Rows.Add(dr);
            dr["AgeGroup"] = "13-18";
            dr["AgeGroupID"] = "Teen";
            ds.Tables[0].Rows.Add(dr);
            dr["AgeGroup"] = "19 above";
            dr["AgeGroupID"] = "Adult";
            ds.Tables[0].Rows.Add(dr);
        }
        return ds.Tables[0];
    }

You also can retrieve data from database to show it in DataGrid, here I only show 3 category to make us understand quickly about DropDownList in an editable DataGrid. Next is the Item Command syntax to handle an Event when someone click a button with a specific command:

protected void dgEmployee_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "EditEmployee")
        {
            dgEmployee.EditItemIndex = e.Item.ItemIndex;
        }

else if (e.CommandName == "UpdateEmployee")
        {
            int iEmployeeID = Convert.ToInt32(e.CommandArgument);

            DropDownList ddlAgeGroup = (DropDownList)e.Item.FindControl("ddlAgeGroup");
            string AgeGroupID = ddlAgeGroup.SelectedItem.Value;

//your database connection and command syntax to update Employee AgeGroupID goes here
//for example "update tblEmployee set AgeGroupID = @AgeGroupID"
        

            dgEmployee.EditItemIndex = -1;
        }
        else if (e.CommandName == "CancelEmployee")
        {
            dgEmployee.EditItemIndex = -1;
        }
     BindData();
}

And Below is the BindData systax:

   protected void BindData()
    {
//your database connection and command syntax to select EmployeeID and AgeGroupID
//For example I make use of Data Layer Object and Arraylist to retrieve data from DB
        string sCompanyID = Request.QueryString["CompanyID"].Trim();
        Company oCompany = new Company(sCompanyID);
        Employee[] aryEmployee = oCompany.GetAllEmployee;
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("EmployeeID", Type.GetType("System.String")));
        dt.Columns.Add(new DataColumn("AgeGroup", Type.GetType("System.String")));
        DataRow dr;

  for (int i = 0; i < aryEmployee.Length; i++)
        {
            dr = dt.NewRow();

            //will binded to asp:BoundColumn with DataSource = "EmployeeID"
            dr["EmployeeID"] = aryEmployee[i].EmployeeID;
            //will binded to ASP:TemplateColumn ItemTemplate with DataSource = "AgeGroup"
            dr["AgeGroup"] = aryEmployee[i].AgeGroup;
            dt.Rows.Add(dr);
        }

        dgEmployee.DataSource = dt;
        dgEmployee.DataBind();
}

Conclusion

You now have a fully functional DropDownList in your DataGrid. This is only one of the many features in DataGrids. Check out and explore it, try and see exactly what we can get the most out of it. You'll be pleasantly surprised.

References

Include all the useful links or references that can help users learn about this tutorial:

  1. Microsoft: DataGrid In Place Editing

    Tag Cloud
      checkboxlist datasource   edit update insert in a gridview c#   asp.net cookie shopping cart   httpwebresponse   asp.net tooltip   upload file progress bar asp.net   httpwebrequest .net   cannot start service from the command line or a debugger   httpwebrequest httpwebresponse   asp.net upload ajax progress   formview asp.net   asp.net cookies encryption   asp.net file upload progress bar   datalist control   feedback form in asp.net   asp.net url parameters   smart device application   httpmodule httphandler   asp.net pass data from one page to another   asp.net delegate   generate random number asp.net   frames image gallery thumbnails asp.net   asp.net encryption   tooltip asp.net   httpwebrequest asp.net c#   ajax updatepanel button   form view in asp.net   create httpwebrequest   httpwebrequest create   asp.net listbox control   asp httpwebrequest   formview displaying inserted data   asp.net file upload progress   httpwebrequest in asp.net 2.0   asp.net httpwebrequest   cannot start service from the command line or a debugger. a windows service must   contact us asp.net   "javascript in asp.net"   httpwebrequest vb.net   asp.net random number   httpwebrequest





    Other Related and Popular Articles :

    Simple asp2 feedback form
    A simple way to get user feedback via webpage email.

    Designing a Membership Sign-Up and Login Page in ASP.NET
    How to design user interface for registration and login in ASP.NET

    Validate Email and Domain in a Web Form
    Simple method to validate using javascript and ASP.NET validation control

    Basics of XHTML-MP
    Basics of XHTML-MP

    Activate User Registration by Email in ASP.NET
    How to activate registered user using System.Net.Mail.SMTPClient class

    Implement captcha control library for ASP.NET
    a captcha control, image, image handler, and supression class for form validation


    Author Profile : Hans Candra

    Click here to view Author Profile


    How would you rate the quality of this content?
    Poor Excellent

    Comments

    Leave New Comments


    Article Content copyright by Hans Candra
    Everything else Copyright © by WorldofASP.NET 2008

    Category
    .NET 3.5
    AJAX and ATLAS
    ASP.NET
    C# Programming
    Classic ASP
    Enterprise Systems
    General .NET
    VB.NET Programming
    Announcements
    Earn Cash by writing an article or review
    For more info Click here







    Legend : - Within 3 Days - Within 6 Days - Within 9 Days

    Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
    © 2002-2008 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
    Our Partners : ASP.NET Web Hosting | Windows Web Hosting | ASP.NET Hosting | Phone Card | PHP Directory | Bangkok Hotels |Calling Card