How to Bind DropDownlist Inside GridView in ASP.NET

No.of Views1681
Bookmarked1 times
Downloads 
Votes0
By  Bharat   On  20 Nov 2010 06:11:23
Tag : ASP.NET , List Controls
In this article, i will show to How to Bind DropDownlist Inside GridView in ASP.NET.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In this article, i will show to How to Bind Dropdownlist Inside GridView in ASP.NET.The most of the web application now days is look feel is good and also displaying data in page also very simple.

One of my project , i have to create a page with Gridview also each row has a dropdownlist to select the few countries.The sample Page as like following, 

Image Loading

So now lets try implement as like above.

Implementation

As usual add gridview into the page and then design add template Field four columns.Below i have given html code for design.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="SortID">
                    <ItemTemplate>
                        <%#Eval("sortid")  %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%#Eval("name")  %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddl" runat="server">
                            <asp:ListItem>
                            --Select--asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

In above page design, i have added  DropDownlist in last TemplateField.

<asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:DropDownList ID="ddl" runat="server">
                            <asp:ListItem>
                            --Select--asp:ListItem>
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>

Now i'm going to Bind Country list to DropDownList.

C# Code

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

public partial class Controls_ddgridbinddynamicallyt : System.Web.UI.Page
{protected void Page_Load(object sender, EventArgs e)
    {if (!IsPostBack)
        {
            BindGrid();
        }
    }private void BindGrid()
    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select * from SortTable", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "SortTable");
        GridView1.DataSource = ds;
        GridView1.DataBind();foreach (GridViewRow grdRow in GridView1.Rows)
        {
            DropDownList drdList = new DropDownList();
            drdList = (DropDownList)(GridView1.Rows[grdRow.RowIndex].Cells[2].FindControl("ddl"));// DataBinding of nested DropDownList Control for each row of GridView Control.drdList.DataSource = ds;
            drdList.DataValueField = "SortID";
            drdList.DataTextField = "Country";
            drdList.DataBind();
        }
    }
}

This is straight way Bind data to dropdownlist.There another way as well, you can use the DataRowBound event in GridView.But if use the DataRowBound event, then you may need get the data from database or keep first time selected records in session or view state to in order in this event.

Note:Don't use the SqlConnection class inside the page, better to keep always separate.i have used only for this demosration purpose.

Sql Script for create SortTable.

Sql Script

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[SortTable]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[SortTable](
      [SortID] [int] IDENTITY(1,1) NOT NULL,
      [Name] [varchar](50) NULL,
      [Country] [varchar](50) NULL
) ON [PRIMARY]
END

Download Sample Project

Download source files -2 kb

Conclusion

In this article, You have learned, How to Bind DropDownlist Inside GridView in ASP.NET.

 
Sign Up to vote for this article
 
About Author
 
Bharat
Occupation-Software Engineer
Company-Espranza
Member Type-Junior
Location-India
Joined date-13 Nov 2010
Home Page-
Blog Page-http://usingaspdotnet.blogspot.com
 
 
Other popularSection articles
Comments
By:DelaniDate Of Posted:11/20/2010 10:59:24 PM
Great article
Hello, i try do this for my web project. its help me lot. tnx lot
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top