C# .NET - How to bind a drop down list which is inside a data grid with a table

Asked By anan r on 30-May-08 12:29 AM

Hi,

i am new in C#.net , how do i bind a table to a drop down list. But the drop down list is inside the datagrid in a template coloum.

Please help.

Tnx.




Bind a drop down list which is inside a data grid with a table - Rakesh Vikram replied to anan r on 30-May-08 12:35 AM

Here are some code fragments:

Just put this in the ItemTemplate instead of the EditItemTemplate.

<EditItemTemplate>
<asp:DropDownList runat="server" id="selPublishers"
DataSource='<%# GetPublishersDS() %>'
DataTextField="PublisherName"
DataValueField="PublisherID"
SelectedIndex='<%# GetSelectedPublisher
            ((string)DataBinder.Eval(Container.DataItem,
"PublisherName")) %>' />
</EditItemTemplate>

Note the DataSource statement that sets the datasource to
"GetpublishersDS()", which is a function defined in the code-behind
that returns a http://www.dotnet247.com/247reference/System/Data/DataTable.aspx for the datasource. Binding happens when the
http://www.dotnet247.com/247reference/System/Web/UI/WebControls/DataGrid.aspx is bound.

Check this link for more details -

http://msdn.microsoft.com/en-us/library/aa289519(VS.71).aspx

http://p2p.wrox.com/topic.asp?TOPIC_ID=5756

Hope this help you out.

Sunil Lakshkar replied to anan r on 30-May-08 12:35 AM

Hi,

Use dropdown inside templatefield as follows:

<asp:DropDownList ID="drpResource" width="100%" CssClass="TableFontSmallNB" runat="server" DataSourceID="SqlResourceDataSource"
  DataTextField="Emp_Name" DataValueField="Emp_Id" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlResourceDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:TimesheetServerConnectionString %>"
  SelectCommand="SELECT Emp_Id,Emp_Name FROM dbo.Employee ORDER BY FirstName,LastName">
</asp:SqlDataSource>

check this - Santhosh N replied to anan r on 30-May-08 12:37 AM

check this link on how to go about this..

http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_23097063.html

In grid view Row datab bound event.... - Vasanthakumar D replied to anan r on 30-May-08 12:41 AM

Hi,

try the below code..

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

DropDownList ddl = new DropDownList();

ddl = (DropDownList)e.Row.Cells[Cell No].FindControl("Template DropDownId");

//Code to bind the dropdownlist...

}

Go thr this to bind ddl to table - Sagar P replied to anan r on 30-May-08 01:01 AM

You have to handle a ItemDatabound event of grid and have to use findcontrol to give a datasource to dropdownlist. Like;

private void DataGrid1_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{

DropDownList list = (DropDownList) e.Item.Cells[2].Controls[];
list.datasource = dtable;
list.DataBind();

}

OR you can do it at design time like;

<asp:DropDownList id="ddlList" runat="server" 
    DataSource="<%# PopulateList %>" DataTextField="Description" 
    DataValueField="Description" >
For more details just go thr this;
http://www.codeproject.com/KB/webforms/DataGridDropDownList.aspx
http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=24105
http://rustemsoft.com/asp_datagrid_columns.htm
Best Luck!!!!!!!!!
Sujit.
Bind Dropdown list in Datagrid - SP replied to anan r on 30-May-08 02:05 AM
<asp:DropDownList ID="Dropdownlist1" runat="Server" DataTextField="Name" DataValueField="Id"></asp:DropDownList>

You can bind this dropdown list in DataGrid's ItemDatabound Event like

DropDownlist ddl1 = (DropDownList) e.Item.FindControl("DropDownList1")
ddl1.DataSource = yourDataTable
ddl1.DataTextField = What you want to show in dropdown
ddl1.DataValueField = Value in the backend of the dropdown (generally Id or primary key field of the table)
ddl1.DataBind()


Try this - sri sri replied to anan r on 30-May-08 02:37 AM
Hi,
try the below code

//Aspx page
<asp:DataGrid 
id="DataGrid1" runat="server"
AutoGenerateColumns="False"
OnItemDataBound="DataGrid1_ItemDataBound">
<Columns>
<asp:BoundColumn DataField="au_fname" HeaderText="au_fname" />
<asp:TemplateColumn>
<HeaderTemplate>
<asp:DropDownList
ID="HeaderDropDown" Runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDown_SelectedIndexChanged" />
</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList
ID="ItemDropDown" Runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDown_SelectedIndexChanged" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>

</asp:DataGrid>
//code behind
protected void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.AlternatingItem ||
e.Item.ItemType == ListItemType.Item)
{
string[] options = { "Option1", "Option2", "Option3" };

DropDownList list = (DropDownList)e.Item.FindControl("ItemDropDown");
list.DataSource = options;
list.DataBind();
}
else if(e.Item.ItemType == ListItemType.Header)
{
string[] options = { "OptionA", "OptionB", "OptionC" };

DropDownList list = (DropDownList)e.Item.FindControl("HeaderDropDown");
list.DataSource = options;
list.DataBind();
}

protected void DropDown_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList list = (DropDownList)sender;

TableCell cell = list.Parent as TableCell;
DataGridItem item = cell.Parent as DataGridItem;

int index = item.ItemIndex;
string content = item.Cells[0].Text;

Response.Write(
String.Format("Row {0} contains {1}", index, content)
);

}

}

Example to solve this - Nadaraja Yogendran replied to anan r on 30-May-08 02:59 AM

 

Your aspx file : GridViewExample.aspx

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="GridViewExample.aspx.cs"

Inherits="WebApplication1.GridViewExample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" OnRowDataBound="gridView_RowDataBound">

<Columns>

<asp:BoundField HeaderText="Employee Name" DataField="EmpName" />

<asp:TemplateField HeaderText="Category">

<ItemTemplate>

<asp:DropDownList ID="dropDownListCategory" runat="server">

</asp:DropDownList>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</div>

</form>

</body>

</html>

 

Codebehind: GridViewExample.aspx.cs


using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

/// Created by:    Nadaraja Yogendran
/// Purpose: Binding dropdownlist in gridview
namespace WebApplication1
{
    public partial class GridViewExample : Page
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            BindEmployeeData();
        }

        protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType.Equals(DataControlRowType.DataRow))
            {
                DropDownList dropDownList = (DropDownList)e.Row.FindControl("dropDownListCategory");
                
                dropDownList.DataTextField = "CatName";
                dropDownList.DataValueField = "CatId";
                dropDownList.DataSource = EmployeeCategory.GetCategories();
                dropDownList.DataBind();
            }
        }
        
        private void BindEmployeeData()
        {
            gridView.DataSource = Employee.GetAllEmployees();
            gridView.DataBind();
        }
    }
    
    public class Employee
    {
        private int empId;
        private string empName;

        public int EmpId
        {
            get { return empId; }
            set { empId = value; }
        }

        public string EmpName
        {
            get { return empName; }
            set { empName = value; }
        }
        
        public static List<Employee> GetAllEmployees()
        {
            List<Employee> employeeList = new List<Employee>();
            Employee employee;
            
            for (int i = 0 ; i < 10; i++)
            {
                employee = new Employee();
                employee.EmpId = i;
                employee.EmpName = "Name  " + Convert.ToString(i);
                
                employeeList.Add(employee);
            }

            return employeeList;
        }
    }

    public class EmployeeCategory
    {
        private int catId;
        private string catName;

        public int CatId
        {
            get { return catId; }
            set { catId = value; }
        }

        public string CatName
        {
            get { return catName; }
            set { catName = value; }
        }

        public static List<EmployeeCategory> GetCategories()
        {
            List<EmployeeCategory> categoryList = new List<EmployeeCategory>();
            EmployeeCategory employeeCategory;

            for (int i = 0; i < 3; i++)
            {
                employeeCategory = new EmployeeCategory();
                employeeCategory.CatId = i;
                employeeCategory.CatName = "Category  " + Convert.ToString(i);

                categoryList.Add(employeeCategory);
            }

            return categoryList;
        }
    }
}
drop down list in side the data grid giving ERROR - anan r replied to SP on 01-Jun-08 08:35 PM

private void DataGrid1_ItemDataBound_1(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)

{

DropDownList ddl_list=(DropDownList)e.Item.FindControl("ddl_dev");

ddl_list.DataSource="MstApplication";

ddl_list.DataTextField="DevEnvironment";

ddl_list.DataValueField="AppId";

ddl_list.DataBind();


it throws the following error.

Object reference not set to an instance of an object.

Solve it like this - SP replied to anan r on 03-Jun-08 06:56 AM

Remove double coutes from the dataTable name like

ddl_list.DataSource = MstApplication;

And then try again.
Solve it like this - SP replied to anan r on 03-Jun-08 06:56 AM

Remove double qoutes from the dataTable name like

ddl_list.DataSource = MstApplication;

And then try again.