Question : Need lots of help on building a dropdown list from a database source

I am trying to build a dropdownlist using the database as source
the table is titled 'userType' .

Once the 'intEventId' is selected base on the title select in my source. I need to populate the dropdownlist with two fields all the names of 'strUserTpyeName' and the Cost field 'fltUserTypeCost' for the intEventId only.

Table Name is: Usertype

   intEventID   strUserTypeName                       fltUserTypeCost

      4      Member                               55.0000      
      4      Students                               40.0000       
      4      Non-member               85.0000       
      4      Member, w/late fee               65.0000       
      4      Student, w/late fee               50.0000       
      4      Non-member, w/late fee   95.0000       

      5      Member                               55.0000      
      5      Non-member               85.0000      
      5      Member, w/late fee               65.0000       
      5      Non-member, w/late fee   95.0000      
 
      6      Member                               55.0000
      6      Non-member               85.0000
      6      Member, w/late fee               65.0000       
      6      Non-member, w/late fee   95.0000       

      7      Member                               35.0000
      7      Non-member               45.0000      
      7      Member, w/late fee               45.0000       
      7      Non-member, w/late fee   55.0000       

            "Center" HeaderText="Payment
Method">
               
                         
                         

               

           


     the data source would be:

        Dim dtVolumeOrder As New DataTable()
        Dim strSelectCommand As String = "SELECT e.dtmEvent, t.strUserTypeName, t.fltUserTypeCost FROM i2Integration_EventRegv45_Event e,i2Integration_EventRegv45_UserType t where (YEAR(e.dtmEvent) = '" + ddlYear.SelectedValue + "' AND MONTH(e.dtmEvent) = '" + ddlMth.SelectedValue + "' AND e.strTitle = '" + DroplistData.SelectedValue.Tostring.replace("'","''") + "') Order by e.dtmEvent"
   
         Using sqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString)
            Using adapPatientBills As New SqlDataAdapter(strSelectCommand, sqlConn)
                adapPatientBills.Fill(dtVolumeOrder)
            End Using
        End Using

I need lot's of help here....
       
    Dim myTable As New DataTable()
    Dim strUserTypeName As New DataColumn("strUserTypeName")    
    Dim fltUserTypeCost As New DataColumn("fltUserTypeCost")

    myTable.Columns.Add(strUserTypeName)
    myTable.Columns.Add(fltUserTypeCost)
   
    Dim ds As New DataSet()
    ds = GetDataSet()
   
    If e.Row.RowType = DataControlRowType.DataRow Then
        categoryID = Int32.Parse(e.Row.Cells(0).Text)
        expression = "CategoryID = " & categoryID
       
        Dim ddl As DropDownList = DirectCast(e.Row.FindControl("DDLPaymentMethodID"), DropDownList)
       
        Dim rows As DataRow() = ds.Tables(0).[Select](expression)

        For Each row As DataRow In rows  
            Dim newRow As DataRow = myTable.NewRow()
            newRow("intEventID") = row("strUserTypeName")
            newRow("strUserTypeName") = row("fltUserTypeCost")
            myTable.Rows.Add(newRow)
        Next
       
        DDLPaymentMethodID.DataSource = myTable
        DDLPaymentMethodID.DataTextField = "strUserTypeName"
        DDLPaymentMethodID.DataValueField = "fltUserTypeCost"
        DDLPaymentMethodID.DataBind()

Answer : Need lots of help on building a dropdown list from a database source

It looks like you are struggling with several issues.  I think the code below will address most of your questions, and will put you on the right path to using the code behind.  This is in VB.Net.

Personally I'm not a fan of the editable gridview, and rather prefer to offer clients edit icons that open modal dialogs to edit records.  It gives you much more control over editing records, and the code is much cleaner.  But, if it's your requirement to make an editable gridview, then go for it.

This example shows a standard gridview for clarity. Additional formatting markup has also been removed so you can see the core pieces.  Below is the markup.

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="Expert._Default" %>

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

http://www.w3.org/1999/xhtml" >

   


   
   

       
       
       

       

       
           
               
               
               
           

       

   

   



Note, this doesn't have all the markup your example indicated, but it does contain your month and year dropdown lists.  Those will be populated by for/each loops in the code behind.  The ddlUserType list is there to address your question about displaying a concatenated name and cost in the list.  Again, your interface is more complex than this, but this will show you the core functionality that I think you are aiming for.

Here is the code behind.  To access the code behind, click on the second icon in Solution Explorer with the caption, "Show All Files", then expand the directory next to your aspx file.

The comments above each method explain a little about what they do.  Here are a few highlights:
1. Using for loops, the month and year lists are respectively populated by FillMonthList() and FillYearList().
2. Your User Type dropdown list is populated by FillUserTypeList(). This iteratively populates the list one record at a time so you can concatenate the values in the web code, rather than using the DataSource and DataBind methods.
3.  There are a couple of examples of using the Command object to execute stored procedures to retrieve data - GetEvents() and GetUserTypes().  I strongly recommend that you put your data queries into stored procedures, rather than constructing them inline within your web code.  It reduces the risk of SQL Injection attacks.

Imports System.Data
Imports System.Data.SqlClient

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try
            If Page.IsPostBack = False Then
                'Populate these lists only when the page first loads.
                Call FillMonthList()
                Call FillYearList()
            End If

        Catch ex As Exception
            'Handle exception here.
        End Try

    End Sub

    '''
    ''' Put months in dropdown list.
    '''

    Private Sub FillMonthList()
        For MonthID As Integer = 1 To 12
            Dim MonthName As String = Left(DateAndTime.MonthName(MonthID), 3)
            ddlMonth.Items.Add(New ListItem(MonthName, MonthID))
        Next
        ddlMonth.Items.Insert(0, New ListItem("[Month]", 0))
    End Sub

    '''
    ''' Put next 15 years in dropdown list.
    '''

    Private Sub FillYearList()
        For i As Integer = Now.Year To Now.Year + 15
            ddlYear.Items.Add(New ListItem(i, i))
        Next
        ddlYear.Items.Insert(0, New ListItem("[Year]", 0))
    End Sub

    '''
    ''' Iteratively populate ddlUserType, displaying a concatenated UserType+Cost as text.
    '''

    Private Sub FillUserTypeList(ByVal TitleID As Integer)
        Dim dt As DataTable = GetUserTypes(TitleID)
        For Each dr As DataRow In dt.Rows()
            Dim EventID As Integer = CType(dr.Item("intEventID"), Integer)
            Dim UserType As String = dr.Item("strUserTypeName").ToString().Trim()
            Dim Cost As String = dr.Item("fltUserTypeCost").ToString.Trim()

            Dim liText As String = String.Format("{0} ${1}", UserType, Cost)
            ddlUserType.Items.Add(New ListItem(EventID, liText))
        Next
    End Sub

    '''
    ''' Repopulate gvRegistration when a month or year is selected.
    ''' Called by SelectedIndexChanged events of those dropdown lists.
    '''

    Private Sub LoadRegistrationGrid()

        Dim MonthID As Integer = 0
        Dim YearID As Integer = 0
        Integer.TryParse(ddlMonth.SelectedValue, MonthID)
        Integer.TryParse(ddlYear.SelectedValue, YearID)

        Dim dt As DataTable = Nothing
        If MonthID > 0 AndAlso YearID > 0 Then
            dt = GetEvents(MonthID, YearID)
        End If
        gvRegistration.DataSource = dt
        gvRegistration.DataBind()

    End Sub 'LoadRegistrationGrid

    '''
    ''' Retrieve events for the selected month and year from the database.
    ''' Called by LoadRegistrationGrid().
    '''

    Private Function GetEvents(ByVal MonthID As Integer, ByVal YearID As Integer) As DataTable
        Dim dtOut As DataTable = Nothing

        Dim ConnString As String = System.Configuration.ConfigurationManager.AppSettings("MyConnectionString")

        Using cn As New SqlConnection(ConnString)
            Using cmd As New SqlCommand("sp_EventsGet", cn)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.Add(New SqlParameter("@MonthID", SqlDbType.Int)).Value() = MonthID
                cmd.Parameters.Add(New SqlParameter("@YearID", SqlDbType.Int)).Value() = YearID
                cmd.Connection.Open()

                Dim ds As DataSet = Nothing
                Using da As New SqlDataAdapter(cmd)
                    da.Fill(ds)
                End Using
                dtOut = ds.Tables(0)

                cmd.Connection.Close()
            End Using
        End Using

        Return dtOut
    End Function 'GetEvents

    '''
    ''' Retrieve user types from the database based on the selected title.
    ''' Called by FillUserTypeList()
    '''

    Private Function GetUserTypes(ByVal TitleID As Integer) As DataTable
        Dim dtOut As DataTable = Nothing

        Dim ConnString As String = System.Configuration.ConfigurationManager.AppSettings("MyConnectionString")

        Using cn As New SqlConnection(ConnString)
            Using cmd As New SqlCommand("sp_UserTypesGet", cn)
                cmd.CommandType = CommandType.StoredProcedure
                cmd.Parameters.Add(New SqlParameter("@TitleID", SqlDbType.Int)).Value() = TitleID
                cmd.Connection.Open()

                Dim ds As DataSet = Nothing
                Using da As New SqlDataAdapter(cmd)
                    da.Fill(ds)
                End Using
                dtOut = ds.Tables(0)

                cmd.Connection.Close()
            End Using
        End Using

        Return dtOut
    End Function 'GetUserTypes

    '''
    ''' Event to reload the grid when a new month is selected.
    '''

    Private Sub ddlMonth_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlMonth.SelectedIndexChanged
        Try
            Call LoadRegistrationGrid()
        Catch ex As Exception
            'Handle exception here.
        End Try
    End Sub

    '''
    ''' Event to reload the grid when a new year is selected.
    '''

    Private Sub ddlYear_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlYear.SelectedIndexChanged
        Try
            Call LoadRegistrationGrid()
        Catch ex As Exception
            'Handle exception here.
        End Try
    End Sub
End Class

Good luck.  I hope this helps you out.
Random Solutions  
 
programming4us programming4us