Hi people,

I am working on a asp.net c# project where i need a drop down list and check boxes in a grid view. can any one help me out how to do this.

thanks in advance
shireesha

Recommended Answers

All 6 Replies

Use TemplatedColumn.

Follow this example :

<asp:GridView ID="gvStates" AutoGenerateColumns="false"
     runat="server" OnRowCreated="gvStates_RowCreated">
  <Columns>
    <asp:BoundField HeaderText="State" DataField="Name" />
    <asp:TemplateField HeaderText="Cities">
      <ItemTemplate>
        <asp:DropDownList ID="ddlCities"
AutoPostBack="true" runat="server" 
>
        </asp:DropDownList>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>




protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
       // Create states array and bind it to Grid
       ArrayList states = new ArrayList();

       string[] cities = 
           new string[] { "Portland", "Salem", "Eugene" };
       State state = new State("OR", cities);
       states.Add(state);
       cities = 
           new string[] { "Seattle", "Tacoma", "Olympia" };
       state = new State("WA", cities);
       states.Add(state);

       this.gvStates.DataSource = states;
       this.gvStates.DataBind();
   }
}

protected void gvStates_RowCreated(object sender, 
    GridViewRowEventArgs e)
{
   if (!IsPostBack)
   {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           // Bind drop down to cities
           DropDownList ddl = 
             (DropDownList)e.Row.FindControl("ddlCities");
           ddl.DataSource = ((State)e.Row.DataItem).Cities;
           ddl.DataBind();
       }
   }
}

Tell if it solved.

Follow this example :

<asp:GridView ID="gvStates" AutoGenerateColumns="false"
     runat="server" OnRowCreated="gvStates_RowCreated">
  <Columns>
    <asp:BoundField HeaderText="State" DataField="Name" />
    <asp:TemplateField HeaderText="Cities">
      <ItemTemplate>
        <asp:DropDownList ID="ddlCities"
AutoPostBack="true" runat="server" 
>
        </asp:DropDownList>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>




protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
       // Create states array and bind it to Grid
       ArrayList states = new ArrayList();

       string[] cities = 
           new string[] { "Portland", "Salem", "Eugene" };
       State state = new State("OR", cities);
       states.Add(state);
       cities = 
           new string[] { "Seattle", "Tacoma", "Olympia" };
       state = new State("WA", cities);
       states.Add(state);

       this.gvStates.DataSource = states;
       this.gvStates.DataBind();
   }
}

protected void gvStates_RowCreated(object sender, 
    GridViewRowEventArgs e)
{
   if (!IsPostBack)
   {
       if (e.Row.RowType == DataControlRowType.DataRow)
       {
           // Bind drop down to cities
           DropDownList ddl = 
             (DropDownList)e.Row.FindControl("ddlCities");
           ddl.DataSource = ((State)e.Row.DataItem).Cities;
           ddl.DataBind();
       }
   }
}

Tell if it solved.

can you pl explain me what is State here?
State state = new State("OR", cities);

I am getting an error saying
": CS0246: The type or namespace name 'State' could not be found (are you missing a using directive or an assembly reference?)"

You have to use your own Datasource instead of states and cities in the line this.gvStates.DataSource = states; You can use your own function or ObjectDataSource as you like..

Please clarify what you have to do.

Use this sample


HTML Source(.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DemoPage1.aspx.cs" Inherits="DemoPage1" %>
<!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 id="Head1" runat="server">
    <title>GridView Sample By Ramesh S</title>

    <script type="text/javascript">
        function selectUnselectCheckboxes(chkHeaderCtrl, chkBoxIdInGrid, gridViewName) {
            var chkbox = chkBoxIdInGrid;
            gridViewName = document.getElementById(gridViewName);
            var grdCount = gridViewName.rows.length;

            //the controls in the gridview will have the following suffix in their ids 'GridView1_ctl0n'
            //the first element starts with 2 e.g. GridView1_ctl02_chkEmployee(first element)... GridView1_ctl10_chkEmployee(9th element)
            for (i = 2; i <= grdCount; i++) {
                var ctlIndex = eval(i);
                if (ctlIndex < 10)
                    ctlIndex = '0' + ctlIndex;

                var chkBoxIdInGrid = gridViewName.id + '_ctl' + ctlIndex + '_' + chkbox;
                chkBoxIdInGrid = document.getElementById(chkBoxIdInGrid);

                if (chkBoxIdInGrid != null) {
                    //if the header checkbox is checked, then check the checkboxes in the grid
                    if (document.getElementById(chkHeaderCtrl).checked == true)
                        chkBoxIdInGrid.checked = true;
                    else
                        chkBoxIdInGrid.checked = false;
                }
            }
        }  
    
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="100%">
            <tr>
                <td>
                    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="500px"
                        BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
                        CellPadding="4" OnRowDataBound="GridView1_RowDataBound">
                        <RowStyle BackColor="White" ForeColor="#003399" />
                        <Columns>
                            <asp:TemplateField>
                                <HeaderTemplate>
                                    <asp:CheckBox ID="chkSelectAll" ToolTip="Select/Unselect all employees" onclick="selectUnselectCheckboxes(this.id, 'chkEmployee', 'GridView1');"
                                        runat="server" />
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkEmployee" runat="server" Checked='<%# Bind("Is_Eligible") %>' />
                                </ItemTemplate>
                                <HeaderStyle HorizontalAlign="Center" />
                                <ItemStyle HorizontalAlign="Center" Width="50px" />
                            </asp:TemplateField>
                            <asp:BoundField DataField="EmpName" HeaderText="Name">
                                <HeaderStyle HorizontalAlign="Left" />
                            </asp:BoundField>
                            <asp:BoundField DataField="EmpCode" HeaderText="Code">
                                <HeaderStyle HorizontalAlign="Left" />
                            </asp:BoundField>
                            <asp:TemplateField HeaderText="Dept">
                                <ItemTemplate>
                                    <asp:DropDownList ID="ddlDept" DataTextField="Dname" DataValueField="Deptno" DataSource="<%#GetAllDept()%>"
                                        runat="server">
                                    </asp:DropDownList>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
                        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
                        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
                        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
                    </asp:GridView>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

C# code to be placed in code behind

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

public partial class DemoPage1 : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }

    private void BindGridView()
    {
        DataTable dtEmp = new DataTable();

        dtEmp.Columns.Add("Is_Eligible", System.Type.GetType("System.Boolean"));
        dtEmp.Columns.Add("EmpName", System.Type.GetType("System.String"));
        dtEmp.Columns.Add("EmpCode", System.Type.GetType("System.Int16"));
        dtEmp.Columns.Add("Deptno", System.Type.GetType("System.Int16"));

        dtEmp.Rows.Add(new object[] { true, "Kannan", 1001, 10 });
        dtEmp.Rows.Add(new object[] { true, "Arun", 1001, 10 });
        dtEmp.Rows.Add(new object[] { false, "Jackson", 1001, 30 });
        dtEmp.Rows.Add(new object[] { true, "Raja", 1001, 20 });
        dtEmp.Rows.Add(new object[] { false, "John", 1001, 30 });

        GridView1.DataSource = dtEmp;
        GridView1.DataBind();
    }

    public DataTable GetAllDept()
    {
        DataTable dtDept = new DataTable();

        dtDept.Columns.Add("Deptno", System.Type.GetType("System.Int16"));
        dtDept.Columns.Add("Dname", System.Type.GetType("System.String"));

        dtDept.Rows.Add(new object[] { 10, "Accounts" });
        dtDept.Rows.Add(new object[] { 20, "Sales" });
        dtDept.Rows.Add(new object[] { 30, "Operations" });

        return dtDept;
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DropDownList ddlDeptNo = (DropDownList)e.Row.FindControl("ddlDept");
            string deptNo = ((System.Data.DataRowView)(e.Row.DataItem)).Row.ItemArray[3].ToString();
            if (ddlDeptNo != null)
            {
                ddlDeptNo.SelectedValue = deptNo;
            }

        }
    }
}

what exactly i need is...i am trying to get data from sql server database and populate in grid view and in that grid view i have edit and delete buttons for each row. when i click on edit button the row should become editable like in the first column there will be dropdown and in the second column there will be check box so the user can select the data from drop down and mark the check box and save the row which should get updated back to database and when the user clicks on delete button that row gets deleted from database.This is exact scenario i need. Can any one help me out in this. If any one can give me some links or code to do this , it'l be very helpful..

thanks in advance...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.