简体   繁体   中英

generic function/sub to fill a vb.net combobox from a module

trying to fill a combobox using a generic routine in a Module in vb.net 2010. I am passing to the sub the variable formname.comboboxname and splitting it into 2, running a query and this is where I can't go further. I need to do this because I have quite a few forms and comboboxes to fill, thought a generic method in one module would be great.

I may break down and do a dataset for each combobox but this certainly should work and would be my preferred choice.

in the form code I call it with --- loadComboBoxOrHelp("FrmArchive.cmbSrcType") and this is in my module, some code is commented just to show what I have tried so far. And of course the line above the CTYPE works if I uncomment it but then its not generic. As you can guess from the name of the function, i want to fill a combobox OR a help text field but I have not done that code yet, I assume once the combobox part works I can guess out the text box part. The query will be the same, just a text box instead of combobox.

The CTYPE is my error, I am trying to do this from a module so its very generic, if I put it in the forms code of course it works. * * I took out the SQL as it was confusing the issue. I am now calling it this with loadComboBoxOrHelp(Me, cmbSrcType)

Public Sub loadComboBoxOrHelp(ByVal formName, ByVal boxName)
    Try
        CType(formName.Controls(boxName), ComboBox).Items.Add("ABC") 'myReader.GetString("lookupValue").ToString)
    Catch ex As Exception
        MessageBox.Show("Error while retrieving records on table Lookups..." & ex.Message, "Lookups Table")
    Finally
        If conn.State = ConnectionState.Open Then conn.Close()
    End Try
End Sub

End Module

Well, I think you could pass directly the ComboBox to the function, but if you really want to use a string then you need to find a way to retrieve the Form and combo instance from the name passed in

Public Sub loadComboBoxOrHelp(ByVal boxName)
    Dim words = boxName.Split(".") 
    Dim formName = Application.OpenForms(words(0))  
    Dim cmbBox = formName.Controls(words(1))
    ......

As a side note. Use a parameterized query to build sql commands, not string concatenation. Also if you are in full control of what is passed to the sql command it is better to avoid the quoting/unquoting of values

    conn.Open()
    myCommand.Connection = conn
    Dim query = "SELECT name, lookupValue " _
                & "FROM lookups " _
                & "WHERE name = @bxname"
    myCommand.CommandText = query
    myCommand.Parameters.AddWithValue("@bxname", boxName)
    myReader = myCommand.ExecuteReader()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM