Thursday 31 March 2011

Dropdownlist inside the Gridview in ASP.NET


Introduction: Hello friends, in this article i will explain that how we can bind dropdownlist inside  the gridview. This is very interesting article for every .net developers. 

Implementation: Create a new website add a page named dd_inside_the_gridview.aspx. Drag and drop the gridview  at  this page from the toolbox. Below i am giving the html code for the .aspx page.

Code for dd_inside_the_gridview.aspx page:

<form id="form1" runat="server">
    <div>
    </div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
        CellPadding="4" ForeColor="Black" GridLines="Horizontal" Height="241px"
        Width="374px">
            <Columns>
                <asp:TemplateField HeaderText="ID">
                    <ItemTemplate>
                        <%#Eval("id")  %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%#Eval("name")  %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="designation">
                    <ItemTemplate>
                        <asp:DropDownList ID="dd_desghnation" runat="server">
                            <asp:ListItem> --Select--</asp:ListItem>
                         
                        </asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
            <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
            <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
    </form>


Code for dd_inside_the_gridview.aspx.cs page:

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.Data;
using System.Configuration;
// use above three namespaces for this article

public partial class dd_inside_the_gridview : System.Web.UI.Page
{
    DropDownList bind_dropdownlist;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Page.IsPostBack == false)
        {
            // here i am calling the function which bind the gridview
            bind_gridview_with_dropdownlist();
        }
    }
    private void bind_gridview_with_dropdownlist()
    {
        // here i am declare a connectionstring to attach the database
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString);
        con.Open();
        // here i am definning the sql query which will used for the binding of the gridview and declare the SqlDataAdapter
        SqlDataAdapter adp = new SqlDataAdapter("select * from tb_designation", con);
        // here i am declare the dataset to fill the gridview
        DataSet ds = new DataSet();
        // here i am filling the SqlDataAdapter with the dataset
        adp.Fill(ds, "tb_designation");
        //here i am binding the gridview with the dataset ds 
        GridView1.DataSource = ds;
        GridView1.DataBind();
        // here i am using the foreach loop to bind the gridview with the database
        foreach (GridViewRow grdRow in GridView1.Rows)
        {
            // here i am definning the property of the DropDownList as bind_dropdownlist
           // DropDownList bind_dropdownlist = new DropDownList();
            // here i am finding the  DropDownList from the gridiew for        binding
            bind_dropdownlist = (DropDownList)(GridView1.Rows[grdRow.RowIndex].Cells[2].FindControl("dd_desghnation"));
            // here i am binding the DropDownList with the dataset ds
            bind_dropdownlist.DataSource = ds;
            // here i am set the DropDownList's DataValueField as id
            bind_dropdownlist.DataValueField = "ID";
            // here i am set the DropDownList's DataTextField as designation which display the designation in the dropdownlist after fetching the data from database
            bind_dropdownlist.DataTextField = "designation";
            bind_dropdownlist.DataBind();
        }
    }
}
Below i am displaying the outout of this program in the image:

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiIczcoyBXRWkuKKEnB_ihliNz3fvQPfDZQiv6QvEmcHgB1VIYsGtSofN5a01VCtgOYK17N5uJcLuUIaID3RhL0Yn3InTgJj1SzgMyXfUf1sBx_THmfOrH26u8ozCw6Z5pn8MYbpV9h7Gn7/s320/drop-down.jpg




SQl script for the table tb_designation:

/****** Object:  Table [dbo].[tb_designation]    Script Date: 03/08/2011 18:59:32 ******/
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_designation]') AND type in (N'U'))
DROP TABLE [dbo].[tb_designation]
GO
/****** Object:  Table [dbo].[tb_designation]    Script Date: 03/08/2011 18:59:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tb_designation]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[tb_designation](
     [ID] [int] IDENTITY(1,1) NOT NULL,
     [Name] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
     [designation] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
END
GO
SET IDENTITY_INSERT [dbo].[tb_designation] ON
INSERT [dbo].[tb_designation] ([ID], [Name], [designation]) VALUES (1, N'Bharat', N'manager')
INSERT [dbo].[tb_designation] ([ID], [Name], [designation]) VALUES (2, N'John', N'clerck')
INSERT [dbo].[tb_designation] ([ID], [Name], [designation]) VALUES (3, N'vikas', N'director')
INSERT [dbo].[tb_designation] ([ID], [Name], [designation]) VALUES (4, N'ajay', N'developer')
INSERT [dbo].[tb_designation] ([ID], [Name], [designation]) VALUES (5, N'manoj', N'designer')
INSERT [dbo].[tb_designation] ([ID], [Name], [designation]) VALUES (6, N'vishal', N'content writer')
SET IDENTITY_INSERT [dbo].[tb_designation] OFF

Conclusion: Dear friends, through this article you have learned that how we can bind dropdownlist inside the gridview.




 

24 comments:

  1. Thanks a lot.. this is the one solution i expected..

    ReplyDelete
    Replies
    1. Hey sathish!!!! Thanks sir for your comment. You can also give me some suggestions to Improve my next articles.

      Thanks

      Regards
      Bharat Bhushan

      Delete
  2. Great post..but you need give the clear code ..

    ReplyDelete
    Replies
    1. Hi!!! Bhaskar,

      Brother i am giving the complete code with the description. Commented lines means the complete description of the code. These commented lines helps to the developer to understand the complete code.

      Thanks

      Regards
      Bharat Bhushan

      Delete
  3. using Microsoft enterprise library also, u can do database operation please check... http://aspnettutorialonline.blogspot.com/2012/04/insert-delete-update-records-in.html

    ReplyDelete
  4. There is a problem with this code. The dropdownlist doesn't contain a list of items.

    ReplyDelete
    Replies
    1. On the my end there is not any error inside this code. It is running greatly.Please debug it properly when u will run and check the database that there is values available or not inside the table.

      Thanks.

      Regards

      Bharat Bhushan

      Delete
  5. Replies
    1. Hi!!! Gaurang Its mine pleasure dear.. If you have any suggestion to improve the blog. You can also send me your expensive suggestions..

      Delete
  6. Drop down contains set of values not filling like above the pic its binding a common values for all drop down

    ReplyDelete
    Replies
    1. In the image i am displaying the different values because of the showing the values for the user. and at the binding time these values will come accoring to the sql query in asc or desc order or according to the order, which u'll use..

      Delete
  7. Is it neceessary to bind gridview
    while binding the dropdown list

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Dear Friend i have used the same code every thing is fine but i am getting first value in drop down. plz advice me Shivakuti(at)gmail.com

    ReplyDelete
    Replies
    1. Hi!! shivakaruna Thankx you sir. Please feel free to get in touch with my blog and you can also give us your expensive suggestions to improve this blog. and read this article. This will help you to solve your problem
      http://www.aspsnippets.com/Articles/Bind-DropDownList-in-ItemTemplate-of-TemplateField-in-ASPNet-GridView.aspx

      Thanks
      using asp.net

      Delete
  10. Hello,
    Thank you very much this code really helped me a lot.

    ReplyDelete
  11. thank you sir this code really helped me a lot.
    But my Question is that i want default value of row is already selected

    ReplyDelete
  12. Sir,you gave a great code,but my question is after selecting value from dropdownlist ,I want to update data of designation in database.

    ReplyDelete
    Replies
    1. Hi!! Kartika. Thanks a lot sir. If you want to update the record after selecting the option from the dropdownlist, firstly place and bind the dropdownlist inside the edititemtemplate of the grid then in the updating evet find the dropdown and after finding bind it and write the update code.

      Thanks
      Using Asp.net

      Delete
  13. Hi, Nice code for Dropdownlist inside the Gridview in ASP.NET.Code is Simple and useful to learn.Thanks for your support.

    -Aparna
    Theosoft

    ReplyDelete
  14. thanks very much
    i had a big problem with Drop down because i'm a beginner

    ReplyDelete
  15. Having the same code but M getting null value in row while checking with break point....
    :(

    ReplyDelete