Dropdown lists in gridviews on selected index changed.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kalkin
    New Member
    • Nov 2009
    • 6

    Dropdown lists in gridviews on selected index changed.

    Hi

    Is it possible to change the data source of a dropdown list in a gridview from another dropdown list selected index changed method in the same gridview?

    for example I have a dropdown that needs to change its contents depending on what is chosen in the previous cell of the gridview, which is also a dropdown list.

    Any Help would be much appreciated

    Thanks
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    Have you considered accessing the row that the DropDownList belongs to using the NamingContainer ?

    For example:
    VB:
    Code:
    Protected Sub FirstDropDownList_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles FirstDropDownList.SelectedIndexChanged
    
      'Grabbing a reference to the row that the DropDownList belongs to:
      Dim gridViewRowDdlBelongsTo As GridViewRow  = Ctype( Ctype(sender,Control).NamingContainer, GridViewRow)
    
      'Grabbing a reference to the second DropDownList in the row:
       Dim secondDropDownList As DropDownList = CType(gridViewRowDdlBelongsTo.FindControl("secondDropDownList"),DropDownList)
    
      'Now you just need to set the data source for the secondDropDownList
      'according to the selection in the firstDropDownList
      '.......
    End Sub
    C#:
    Code:
    protected void FirstDropDownList_SelectedIndexChanged(object sender, EventArgs e)    {       
      // Grabbing a reference to the row that the DropDownList belongs to:
      GridViewRow gridViewRowDdlBelongsTo = (GridViewRow)(((Control)sender).NamingContainer);   
    
      // Grabbing a reference to the second DropDownList in the row:
      DropDownList secondDropDownList = (DropDownList)gridViewRowDdlBelongsTo .FindControl("secondDropDownList");
    
      // Now you just need to set the data source for the secondDropDownList
      // according to the selection in the firstDropDownList
      // ....
    }
    -Frinny

    Comment

    • Kalkin
      New Member
      • Nov 2009
      • 6

      #3
      RE: Frinavale

      Thank you for replying so promptly. I have tried what you suggested, and i must admit that i am quite new to programming so i might have misunderstood. But here is my code never the less.

      Code:
      Protected Sub ddMerchCat_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
              Dim objRecordsource As New Bestvest_DataAccess.cDataAccess
              Dim dstSubMerch As New DataSet
              Dim strMerch As String
              Dim ddMerchCat As DropDownList = CType(gvRentalIncome.Rows(0).FindControl("ddMerchCat"), DropDownList)
      
              Dim drwSubMerch As GridViewRow = CType(CType(sender, Control).NamingContainer, GridViewRow)
             
              strMerch = Replace(ddMerchCat.SelectedItem.Text, " ", "")
              dstSubMerch = objRecordsource.getRecordSet("Select * from tbl_Merc_" & strMerch & "")
      
              Dim ddSubMerch As DropDownList = CType(drwSubMerch.FindControl("ddSubMerchCat"), DropDownList)
              ddSubMerch.DataSource = dstSubMerch
              ddSubMerch.DataValueField = "" & strMerch & "ID"""
              ddSubMerch.DataTextField = "Type"
              ddSubMerch.DataBind()
      Last edited by Frinavale; Nov 17 '09, 02:12 PM. Reason: Please post code in [code] ... [/code] tags. Added code tags.

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Is there a problem with your code?
        I don't see anything wrong...

        Here's a working example of what you're trying to do. I have 2 columns in my GridView. The first column contains a DropDownList named "ddl1" and the second column contains a DropDownList named "ddl2". By default ddl1 displays numbers 1-10 and ddl2 doesn't have any items. If you select an even number in ddl1 then ddl2 is populated with letters but if you select an odd number in ddl1 then ddl2 is populated with a list of roman numerals.

        In my Default.aspx page I have the following (very simple GridView):
        Code:
        <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="MyNamespace._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>Testing DropDownLists</title>
        </head>
        <body>
            <asp:GridView ID="theGridView" runat="server" AutoGenerateColumns="false">
                <Columns>
                <asp:TemplateField HeaderText="First DropDownList" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate> <asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddl1_OnSelectedIndexChanged"></asp:DropDownList></ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Second DropDownList" ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate><asp:DropDownList ID="ddl2" runat="server"></asp:DropDownList></ItemTemplate>
                </asp:TemplateField>
                </Columns>
            </asp:GridView>
            </form>
        </body>
        </html>
        And here is my very simple VB code:
        Code:
        Partial Public Class _Default
          Inherits System.Web.UI.Page
        
          Private src As DataView 'used as the datasource for the GridView
          Private ddl1Source As List(Of ListItem) 'used as the datasource for the first DropDownList in the GridView
          
        
          ''' <summary>
          '''  Creates a simple data source to be used in the GridView
          ''' </summary>
          ''' <remarks></remarks>
          Private Sub GenerateSource()
            'Only creating a new source if one doesn't already exist in session.
            If Session("src") Is Nothing Then 
              Dim tbl As New DataTable
              tbl.Columns.Add("ID")
              tbl.Columns.Add("first")
              tbl.Columns.Add("second")
        
              For i As Integer = 1 To 10
                Dim r As DataRow = tbl.NewRow()
                r("ID") = i.ToString
                tbl.Rows.Add(r)
              Next
              src = New DataView(tbl)
              Session("src") = src
                     
              'Generating the default source for the first DropDownList:
              ddl1Source = New List(Of ListItem)
              For i As Integer = 1 To 10
                ddl1Source.Add(New ListItem(i.ToString, i.ToString))
              Next
              Session("ddl1Source") = ddl1Source 
            Else
              src = CType(Session("src"), DataView)
              ddl1Source = CType(Session("ddl1Source"), List(Of ListItem))
            End If
          End Sub
        
          ''' <summary>
          '''  Handles the Page PreRender event. This happens just before the
          ''' the page's controls are rendered as HTML and sent to the browser.
          ''' </summary>
          ''' <param name="sender">The Object that raised the event (the Page).</param>
          ''' <param name="e">The EventArgs for the event.</param>
          ''' <remarks></remarks>
          Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
            If IsPostBack = False Then
              'If it's the first time loading the page, generating the data source
              'for the GridView and binding to it.
              GenerateSource()
              theGridView.DataSource = src
              theGridView.DataBind()
            End If
          End Sub
        
          ''' <summary>
          ''' Handles theGridView's RowDataBound Event. Here I am setting the
          ''' data source for the first DropDownList and binding it to it.
          ''' </summary>
          ''' <param name="sender">The Object that raised the event (theGridView).</param>
          ''' <param name="e">The GridViewRowEventArgs for the event containing information about the row being bound.</param>
          ''' <remarks></remarks>
          Private Sub theGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles theGridView.RowDataBound
            If (e.Row.FindControl("ddl1") IsNot Nothing) Then
              CType(e.Row.FindControl("ddl1"), DropDownList).DataSource = ddl1Source
              CType(e.Row.FindControl("ddl1"), DropDownList).DataBind()
            End If     
          End Sub
        
          ''' <summary>
          '''  Handles the First DropDownList's SelectedIndexChanged Event.
          '''  Here we check what was selected and generate a DataSource for
          '''  the second DropDownList.
          ''' </summary>
          ''' <param name="sender">The Object that raised the event (the ddl1 DropDownList)</param>
          ''' <param name="e">The EventArgs for the event.</param>
          ''' <remarks></remarks>
          Protected Sub ddl1_OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
            'Grabbing a reference to the ddl1 that raised the event
            Dim ddl1 As DropDownList = CType(sender, DropDownList)
        
            'Grabbing a reference to the GridViewRow that the ddl1 belongs to 
            'so that I can grab a reference to the ddl2 that belongs to that row
            Dim gridViewRowDdlBelongsTo As GridViewRow = CType(CType(sender, Control).NamingContainer, GridViewRow)
          
            'Grabbing a reference to ddl2 that is in the same row as ddl1
            Dim ddl2 As DropDownList = Nothing
            If gridViewRowDdlBelongsTo IsNot Nothing
              ddl2 = CType(gridViewRowDdlBelongsTo.FindControl("ddl2"), DropDownList)
            End If
        
            'Generating the data source for ddl2 depending on what was selected 
            'in ddl1
            Dim ddl2Source As List(Of ListItem) 'used as the datasource for the second DropDownList in the GridView
            ddl2Source = New List(Of ListItem)
            If ddl1.SelectedIndex Mod 2 = 0 Then
              'generate letters as source for second list
              ddl2Source.Add(New ListItem("A", "1"))
              ddl2Source.Add(New ListItem("B", "2"))
              ddl2Source.Add(New ListItem("C", "3"))
              ddl2Source.Add(New ListItem("D", "4"))
            Else
              'generate roman numerals for source for second list
              ddl2Source.Add(New ListItem("i", "1"))
              ddl2Source.Add(New ListItem("ii", "2"))
              ddl2Source.Add(New ListItem("iii", "3"))
              ddl2Source.Add(New ListItem("iv", "4"))
            End If
         
            'Setting the datasource for ddl2 in the row, and binding to it.
            If ddl2 IsNot Nothing Then
              ddl2.DataSource = ddl2Source
              ddl2.DataBind()
            End If
          End Sub
        End Class

        Comment

        • Kalkin
          New Member
          • Nov 2009
          • 6

          #5
          Thanks Frinavale, have it working now! I am an idiot and my datasource was empty.

          Thanks again

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            I'm glad you got it to work :)

            -Frinny

            Comment

            Working...