Вопрос

i want to pick payrollcode when listbox is selected though list should appear as payrollname.Once I have the paycode i can then use it in another query.I have a php background so this is alittle tricky for me.

 Dim cmd As New SqlCommand("select tblPayrollCode.payrollcode_name ,tblPayrollCode.payrollcode_code  from tblPayrollCode where tblPayrollCode.systemcode_id=0 and tblPayrollCode.deduction= 'false'", Getconnect)
    Dim dr As SqlDataReader
    Getconnect()
    dr = cmd.ExecuteReader
    While dr.Read
        lsttrans.Items.Add(dr.Item("payrollcode_name"), payrollcode_code)
    End While
    dr.Close()
Это было полезно?

Решение

Create a class to create objects that keep each display item/data pair. The class needs to specify an overriden ToString method. This method overrides the ToString method of the base class (Object) to ensure that your display item and not the class name is displayed in the list box.

Public Class CListItem

Private m_sItemData As String
Private m_sItemDisplay As String

Public Sub New(ByVal sValue As String, ByVal sData As String)
    m_sItemData = sData
    m_sItemDisplay = sValue
End Sub

Public Overrides Function ToString() As String
    Return m_sItemDisplay
End Function

Public Property ItemData() As String
    Get
        Return m_sItemData
    End Get
    Set(ByVal Value As String)
        m_sItemData = Value
    End Set
End Property

Public Property ItemDisplay() As String
    Get
        Return m_sItemDisplay
    End Get
    Set(ByVal Value As String)
        m_sItemDisplay = Value
    End Set
End Property

End Class

Execute the loop like this. This adds a CListItem object to the list box's items collection and displays the first parameter that is passed to the constructor.

While dr.Read
    lsttrans.Items.Add(New CListItem(dr.Item("payrollcode_name").ToString, dr.Item("payrollcode_code").ToString))
End While

You can then retrieve the payrollcode_name and payrollcode_code by adding this code and double clicking on the list box:

Private Sub lsttrans_DoubleClick(sender As Object, e As EventArgs) Handles lsttrans.DoubleClick
    Dim sSelectedDisplay As String = DirectCast(lsttrans.SelectedItem, CListItem).ItemDisplay
    Dim sSelectedData As String = DirectCast(lsttrans.SelectedItem, CListItem).ItemData()

    MessageBox.Show("The selected payrollcode_name is " & sSelectedDisplay & " and the selected payrollcode_code is " & sSelectedData)
End Sub

Другие советы

Adding onto @Guru Josh's answer

While dr.Read
        lsttrans.Items.Add(New CListItem(dr.Item("payrollcode_name"), dr.Item("payrollcode_code")))
    End While

I changed the last bit to the above works fine now.

string col1Value = dr["ColumnOneName"].ToString()

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top