DropDownList GridView and SelectedIndexChanged

This article is written by Pon Saravanan  on 01-Nov-09 Last modified on :06-Jan-10

Subscribe to my RSS Feed!

Using a DropDownList inside a GridView

Dropdowns are one of the most used basic controls just like a textbox. This article explains how to have a DropDownList inside a GridView. Basically the dropdowns have the AutoPostBack property to have a PostBack while selecting items. This can happen in GridView also, and can be implemented like in this article easily. But the understanding of SelectedIndexChanged plays an important role in writing applications with DropDownLists having PostBack.

DropDownList in Markup

Dropdown can be added to the mark up with the help of template columns. I usally keep the dropdown in the EditItemTemplate. But for easy explaining and easy understandings, I am keeping it under ItemTemplate.

Bind the DropDownList

As the DropDownList is inside the ItemTemplate, We have to get that using e.Row.FindControl(). This will give the control, and we can get the Data Source using a SQL Client and assign to the DataSource. Then the DataTextField is the field name which has to be shown in the screen. The DataValueField is the field name which has to be considered as a value for the respective text.

Enable PostBack to get SelectedIndexChanged

As I said just before, the DropDownList often needs PostBack. Implementing the PostBack event is required for that to be handled. Few steps basically we need to do
1) Enable the AutoPostBack by AutoPostBack="true".
2) Add an attribute for SelectedIndexChanged event
3) Write the Event in the code behind without the handles in the sub(refer the sample code here)

Source Code

Mark Up (*.ASPX)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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 id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView runat="server" AutoGenerateColumns="false"  ID="GridView1">
        <Columns>
            <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
            <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
            <asp:TemplateField >
                <ItemTemplate>
                    <asp:DropDownList runat="server" ID="ddlCustomers" AutoPostBack="true"
                    OnSelectedIndexChanged="ddlCustomers_SelectedIndexChanged"></asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    
    </form>
</body>
</html>

Code-Behind(*.VB)

Imports System.Data.SqlClient
Imports System.Data
Partial Class _Default
    Inherits System.Web.UI.Page
    
    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If (Not IsPostBack) Then
            LoadGrid()
        End If
    End Sub
    Private Sub LoadGrid()
        GridView1.DataSource = GetSampleData()
        GridView1.DataBind()
    End Sub
    Private ReadOnly Property ConnectionString() As String
        Get
            Return "Server=.\SQLEXPRESS;Database=NorthWind;Trusted_Connection=True"
        End Get
    End Property
    Private ReadOnly Property Connection() As SqlConnection
        Get
            Dim ConnectionToFetch As New SqlConnection(ConnectionString)
            ConnectionToFetch.Open()
            Return ConnectionToFetch
        End Get
    End Property
    Private Function GetSampleData() As DataView
        Dim SelectQry = "select * from Products"
        Dim SampleSource As New DataSet
        Dim SampleView As DataView
        Try
            Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
            SampleDataAdapter.Fill(SampleSource)
            SampleView = SampleSource.Tables(0).DefaultView
        Catch ex As Exception
            Throw ex
        End Try
        Return SampleView
    End Function
    Private Function GetCustomersData() As DataView
        Dim SelectQry = "select * from Customers"
        Dim SampleSource As New DataSet
        Dim SampleView As DataView
        Try
            Dim SampleDataAdapter As New SqlDataAdapter(SelectQry, ConnectionString)
            SampleDataAdapter.Fill(SampleSource)
            SampleView = SampleSource.Tables(0).DefaultView
        Catch ex As Exception
            Throw ex
        End Try
        Return SampleView
    End Function

    Protected Sub ddlCustomers_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim ddlCustomers = DirectCast(sender, DropDownList)
        Response.Write(ddlCustomers.SelectedValue)
    End Sub

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            Dim ddlCustomers As DropDownList = DirectCast(e.Row.FindControl("ddlCustomers"), DropDownList)
            ddlCustomers.DataSource = GetCustomersData()
            ddlCustomers.DataTextField = "ContactName"
            ddlCustomers.DataValueField = "ContactName"
            ddlCustomers.DataBind()
        End If
    End Sub
  
End Class










No comments added yet

Comments
   
Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    




Spam Bot Trap