Set items of listbox from another form or class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ziycon
    Contributor
    • Sep 2008
    • 384

    Set items of listbox from another form or class

    I'm looking to add items on a listbox on form A from class B which is called from form A. I just don't know how to say add them to the listbox on the active form A from the class B!?
    It's in C#, can anyone help?
  • joedeene
    Contributor
    • Jul 2008
    • 579

    #2
    Originally posted by ziycon
    I'm looking to add items on a listbox on form A from class B which is called from form A. I just don't know how to say add them to the listbox on the active form A from the class B!?
    It's in C#, can anyone help?
    how about referencing the other class/form to a sub that does it, (for vb)

    *this is a sample in VB, perhaps you could recode it into C#, im not real experienced in that particular area.

    Code:
    Public Class Form1
    
    
        Public Shared Sub additemtolistbox(ByVal itemtoadd As String)
            Form1.ListBox1.Items.Add(itemtoadd)
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            myotherclass.subfromotherclasstoadditems()
        End Sub
    End Class
    
    Public Class myotherclass
    
        Public Shared Sub subfromotherclasstoadditems()
            Form1.additemtolistbox("test")
        End Sub
    End Class

    joedeene

    Comment

    • ziycon
      Contributor
      • Sep 2008
      • 384

      #3
      Got it working like this, have an if statement working off a int that counted how many records where in the table and shows all the elements of the returned array that have values. Works perfect.

      Code:
      public string[] getList()
             {
                 DBConnect();
      
                 string[] list = new string[100];
                 int i = 0;
      
                 QueryString = "SELECT title FROM listdat ORDER BY title ASC";
                 command.CommandText = QueryString;
      
                 Reader = command.ExecuteReader();
                 while (Reader.Read())
                 {
                     list[i] = Reader.GetValue(0).ToString();
                     i++;
                 }
      
                 DBDisconnect();
      
                 return list;
             }

      Comment

      • balabaster
        Recognized Expert Contributor
        • Mar 2007
        • 798

        #4
        Hmm, it really depends on the structure of your class... is your listbox going to display each instance of Class B? Or is Class B Implementing a List? Or is Class B an instance of a class that has a list containing the items you wish to populate your listbox with?

        Comment

        Working...