passing control to function

prav_roy

Well-known member
Joined
Sep 10, 2005
Messages
70
Location
Mumbai
Programming Experience
1-3
hi,
i have a class in that i have a function which takes two args, one is string other one is listbox, i am using to fill my listbox, i am calling this function from different form..
VB.NET:
Public Sub Reader(ByVal str As String, ByVal lst As ListBox)
  Dim cmd As New SqlCommand()
  Dim dr As New SqlDataAdapter()
  Dim ds As New DataSet()
  cmd.Connection = dbcon
  cmd.CommandText = str
  dr.SelectCommand = cmd
  Try
    dr.Fill(ds)
    With lst
      .DataSource = ds.Tables(0)
      .DisplayMember = "itemname"
      .ValueMember = "itemno"
    End With
  Catch ex As Exception
    MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
  Finally
    dr = Nothing
    ds = Nothing
  End Try
End Sub


my query is that, can i use same function to pass my other controls like combobox etc by changing second args as control.. if so then how can i do it..
PublicFunction Reader(ByVal str AsString, ByVal lst As Control)

 
Last edited by a moderator:
I added the [ Code] [ /Code] tags to your post for better readability also i change it from a Function to a Sub because your Function wasnt returning a value

but about your question if you're needing to change the actual control on the different form you should change the ByVal keywords to ByRef
by doing this you'll be passing a reference to the actual control not making a copy, so by it being passed ByRef any changes you make to the lst variable will be immediatly shown in the actual listbox on the other form
 
thank you for your reply..
but still im not understood how to carry out this..if i change it to Byref and listbox to control can i pass different control to above code..i tried that but its giving me error saying that DataSourcr is not Member of System.Windows.forms.control
 
That's because a control type does not have a DataSource.... you have to first type cast it back to a ListBox or a Combobox before you can access that property.

And please note, that means you have to type cast it to it's original type. Don't blindly cast it to one thing or another. Use the IS TypeOf construct, check to see if it is a listbox or is a combobox and cast it as needed. If it is neither of those, ignore the control or handle it with a messagebox (althought it's not a run time problem but a design problem at this point).

-tg
 
Back
Top