Friday 27 March 2015

ASP.NET - Gridview with DropDownList inside Header

Watch this example on YouTube:


html

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewWithDDL.aspx.cs" Inherits="WebApplication1.GridViewWithDDL" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
                <Columns>
                    <asp:TemplateField HeaderText="Header">
                        <HeaderTemplate>
                            <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("NAME") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

                </Columns>
            </asp:GridView>

        </div>
    </form>
</body>
</html>







C#

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

namespace WebApplication1
{
    public partial class GridViewWithDDL : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("NAME");
            dt.Rows.Add(new object[] { "Frank" });
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (GridView1.EditIndex == e.Row.RowIndex)
                {
                    DropDownList ddlMonths = (DropDownList)e.Row.Cells[1].FindControl("DropDownList1");
                    ddlMonths.Items.Add(new ListItem("January", "1"));
                    ddlMonths.Items.Add(new ListItem("February", "2"));

                }

            }
        }
    }
}

No comments:

Post a Comment