Listbox in c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lildiapaz
    New Member
    • Jul 2007
    • 38

    Listbox in c#

    How do I display a listbox on another windows form?

    here's what I have, I want to display a new windows form after a button is clicked , and on this windows form. I want to display a listbox with a collection of items on the new created windows form. How do I go about doing this?

    I tried adding a windows form as a new item. But I still don't know how to take the listbox1(with collection of items) from form 1 and display it on form 2 to the user?

    Any help would be appreciated
  • Atran
    Contributor
    • May 2007
    • 319

    #2
    Originally posted by lildiapaz
    How do I display a listbox on another windows form?

    here's what I have, I want to display a new windows form after a button is clicked , and on this windows form. I want to display a listbox with a collection of items on the new created windows form. How do I go about doing this?

    I tried adding a windows form as a new item. But I still don't know how to take the listbox1(with collection of items) from form 1 and display it on form 2 to the user?

    Any help would be appreciated
    Hello:
    Use this code:
    Code:
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                //Form2 is a new form.
                Form Form2 = new Form();
                //Form2 text.
                Form2.Text = "Form2";
                //Show the Form2.
                Form2.Show();
                //
                //Creating a ListBox.
                ListBox ListBox1 = new ListBox();
                //Add items to Listbox1.
                ListBox1.Items.Add("Hello C#");
                ListBox1.Items.Add("Hello VB");
                //Location of Listbox1.
                ListBox1.Location = new Point(12, 12);
                //Add listbox1 to Form2 controls.
                Form2.Controls.Add(ListBox1);
            }
    
        }
    }
    Hope I helped you.

    Comment

    • lildiapaz
      New Member
      • Jul 2007
      • 38

      #3
      Thanks, for the quick response. That did create a new form and a new listbox. but I'm still having a minor problem. What I am trying to do is populate a list of sql databases in that listbox and all the sql tables in another listbox on the new form. I'm able to get all the sql databases when I tested my code, and I believe my code gets all the sql tables. Can you please explain to me, why I am getting incorrect results in the listbox when I try and insert the databases and tables into the listbox's in the new form.

      //get databases
      ListBox listbox1 = new ListBox();
      listbox1.Size = new System.Drawing. Size(200, 100);
      listbox1.Locati on = new System.Drawing. Point(10, 10);
      Form form = new Form();
      DataTable database = myConnection.Ge tSchema("Databa ses");
      foreach (DataRow row in database.Rows)
      listbox1.Items. Add(myConnectio n.GetSchema("Da tabases"));
      form.Controls.A dd(listbox1);
      form.Show();
      //MessageBox.Show ("Database: " + ["database_n ame"]);
      // get tables
      DataTable tables = new DataTable("Tabl es");
      SqlCommand command = myConnection.Cr eateCommand();
      command.Command Text = "SELECT table_name as Name FROM INFORMATION_SCH EMA.Tables WHERE TABLE_TYPE='BAS E TABLE'";
      tables.Load(com mand.ExecuteRea der());


      Thanks

      Comment

      • Plater
        Recognized Expert Expert
        • Apr 2007
        • 7872

        #4
        This seems a bit suspect:
        Code:
        DataTable database = myConnection.GetSchema("Databases");
        foreach (DataRow row in database.Rows)
           listbox1.Items.Add(myConnection.GetSchema("Databases"));
        Shouldn't you be adding in some value from row, and not the whole collection again?
        Maybe like
        Code:
        DataTable database = myConnection.GetSchema("Databases");
        foreach (DataRow row in database.Rows)
           listbox1.Items.Add(row.Cells[3].Value.ToString());
        (There are probably typos in there, but you should see what I mean)

        Originally posted by lildiapaz
        Code:
        //get databases
        ListBox listbox1 = new ListBox();
        listbox1.Size = new System.Drawing.Size(200, 100);
        listbox1.Location = new System.Drawing.Point(10, 10);
        Form form = new Form();   
        DataTable database = myConnection.GetSchema("Databases");
        foreach (DataRow row in database.Rows)
           listbox1.Items.Add(myConnection.GetSchema("Databases"));
        form.Controls.Add(listbox1);
        form.Show();
        //MessageBox.Show("Database: " + ["database_name"]);
        // get tables
        DataTable tables = new DataTable("Tables");
        SqlCommand command = myConnection.CreateCommand();
        command.CommandText = "SELECT table_name as Name FROM INFORMATION_SCHEMA.Tables WHERE TABLE_TYPE='BASE TABLE'";
        tables.Load(command.ExecuteReader());

        Comment

        • lildiapaz
          New Member
          • Jul 2007
          • 38

          #5
          Thanks for the help, I was able to figure out how to insert the new items into the listbox and display them on a new windows form. I have another question though, My listbox on the new form is full of database names, So how do I display the sql tables when the user selects a database from the listbox on the new form and display the sql tables in another listbox on the same form since everything is being created dynamically?

          Can someone please help
          This is what I tried
          //get databases
          Label labels = new Label();
          labels.Location = new System.Drawing. Point(10, 35);
          labels.Text = "Select a database from the list";
          ListBox listbox1 = new ListBox();
          listbox1.Size = new System.Drawing. Size(100, 100);
          listbox1.Locati on = new System.Drawing. Point(10, 60);
          Form form = new Form();
          DataTable database = myConnection.Ge tSchema("Databa ses");
          foreach (DataRow row in database.Rows)
          listbox1.Items. Add(row["database_n ame"]);
          form.Controls.A dd(listbox1);
          form.Controls.A dd(labels);
          string selectedString = listbox1.Select edIndex.ToStrin g();
          // get tables
          ListBox listbox2 = new ListBox();
          listbox2.Size = new System.Drawing. Size(100, 100);
          listbox2.Locati on = new System.Drawing. Point(120, 70);
          Label label = new Label();
          label.Location = new System.Drawing. Point(40, 35);
          labels.Text = "Select a table from list";
          DataTable tables = new DataTable("Tabl es");
          SqlCommand command = myConnection.Cr eateCommand();
          command.Command Text = "SELECT table_name as Name FROM INFORMATION_SCH EMA.Tables WHERE TABLE_TYPE='BAS E TABLE'";
          tables.Load(com mand.ExecuteRea der());
          foreach (DataRow table in database.Rows)
          listbox2.Items. Add(tables);
          form.Controls.A dd(listbox2);
          form.Controls.A dd(label);
          form.Show();

          Originally posted by Plater
          This seems a bit suspect:
          Code:
          DataTable database = myConnection.GetSchema("Databases");
          foreach (DataRow row in database.Rows)
             listbox1.Items.Add(myConnection.GetSchema("Databases"));
          Shouldn't you be adding in some value from row, and not the whole collection again?
          Maybe like
          Code:
          DataTable database = myConnection.GetSchema("Databases");
          foreach (DataRow row in database.Rows)
             listbox1.Items.Add(row.Cells[3].Value.ToString());
          (There are probably typos in there, but you should see what I mean)

          Comment

          • Atran
            Contributor
            • May 2007
            • 319

            #6
            Hello:
            Try this code:
            Code:
            using System;
            using System.Data;
            using System.Drawing;
            using System.Windows.Forms;
            
            namespace WindowsApplication1
            {
                public partial class Form1 : Form
                {
                    Form form;
                    ListBox listbox;
                    DataTable table;
                    public Form1()
                    {
                        InitializeComponent();
                    }
            
                    private void Form1_Load(object sender, EventArgs e)
                    {
                        form = new Form();
                        listbox = new ListBox();
                        table = new DataTable();
                        listbox.Location = new Point(12, 12);
                        listbox.Size = new Size(200, 150);
                        form.Controls.Add(listbox);
                        form.Show();
                        
                        DataTableReader reader = new DataTableReader(dataTable());
                        table.Load(reader);
                        foreach (DataRow row in table.Rows)
                        {
                            for (int i = 0; i < table.Columns.Count; i++)
                            {
                                listbox.Items.Add(row[i] + " ");
            
                            }
                        }
                    }
            
                    private static DataTable dataTable()
                    {
                        DataTable table = new DataTable();
                        DataColumn idColumn = table.Columns.Add("ID", typeof(int));
                        table.Columns.Add("Name", typeof(string));
                        table.PrimaryKey = new DataColumn[] { idColumn };
                        table.Rows.Add(new object[] { 1, "TheScripts" });
                        table.Rows.Add(new object[] { 2, ".Net" });
                        table.Rows.Add(new object[] { 3, "Programmingr" });
                        table.Rows.Add(new object[] { 4, "Fun" });
                        table.AcceptChanges();
                        return table;
                    }
                }
            }
            Atran.

            Comment

            • lildiapaz
              New Member
              • Jul 2007
              • 38

              #7
              Thanks for the help Atran. I have been working on this problem the past few days and I'm still stuck. I wrote a function that returns the datatable, but the problem is that I don't know what to write in my listbox double click event to load the tables.

              Any Suggestions????
              Here's what I have:
              Code:
              private void button1_Click(object sender, EventArgs e)
                      {
              
              get_db_tables();
              }
              
              public DataTable get_db_tables()
                      {
                          //get databases
                          Label labels = new Label();
                          labels.Location = new System.Drawing.Point(10, 35);
                          labels.Text = "Select a database";
                          ListBox listbox1 = new ListBox();
                          listbox1.Size = new System.Drawing.Size(100, 100);
                          listbox1.Location = new System.Drawing.Point(10, 60);
                          listbox1.DoubleClick += new System.EventHandler(this.listBox1_DoubleClick);
                          DataTable database = dbConnect("HPMS3", "Databases");//myConnection.GetSchema("Databases");
                          foreach (DataRow row in database.Rows)
                          {                
                              // if (row.ItemArray[0].ToString() == "HPMS3")
                              // {
                              listbox1.Items.Add(row["database_name"]);
                              //}
                          }
                          Form form = new Form();
                          form.Controls.Add(listbox1);
                          form.Controls.Add(labels);
                          form.Show();
                          // get tables
                          ListBox listbox2 = new ListBox();
                          listbox2.Size = new System.Drawing.Size(140, 100);
                          listbox2.Location = new System.Drawing.Point(150, 60);
                          listbox2.Visible = false;
                          // 
                          //   string[] restrictions = new string[4];
                          //  restrictions[0] = "HPMS3";
                          
                          DataTable tables = dbConnect("HPMS3", "Tables"); //myConnection.GetSchema("Tables", restrictions);
                          foreach (DataRow rowTable in tables.Rows)
                          {
                              for (int i = 0; i < tables.Columns.Count; i++)
                              {
                                  listbox2.Items.Add(rowTable[i].ToString());
                              }
                          }
                              Label label2 = new Label();
                          label2.Location = new System.Drawing.Point(140, 35);
                          label2.Text = "Select table";
                          form.Controls.Add(listbox2);
                          form.Controls.Add(label2);
                          form.Show();
                         return tables;
                      }
              
              private void listBox1_DoubleClick(object sender, EventArgs e)
                      {
                          
                        //DON'T KNOW WHAT CODE TO INCLUDE HERE TO SHOW 
              THE TABLES AFTER THE LISTBOX WITH DATABASES IS CLICKED
              
                      }
              OUTPUT:
              Everything works fine, I am able to connect to the server, show the new form, with a listbox of all the databases. My problem is I don't know how to show the tables in another listbox after a database is selected from the listbox on the same form

              Can anyone help?

              Originally posted by Atran
              Hello:
              Try this code:
              Code:
              using System;
              using System.Data;
              using System.Drawing;
              using System.Windows.Forms;
              
              namespace WindowsApplication1
              {
                  public partial class Form1 : Form
                  {
                      Form form;
                      ListBox listbox;
                      DataTable table;
                      public Form1()
                      {
                          InitializeComponent();
                      }
              
                      private void Form1_Load(object sender, EventArgs e)
                      {
                          form = new Form();
                          listbox = new ListBox();
                          table = new DataTable();
                          listbox.Location = new Point(12, 12);
                          listbox.Size = new Size(200, 150);
                          form.Controls.Add(listbox);
                          form.Show();
                          
                          DataTableReader reader = new DataTableReader(dataTable());
                          table.Load(reader);
                          foreach (DataRow row in table.Rows)
                          {
                              for (int i = 0; i < table.Columns.Count; i++)
                              {
                                  listbox.Items.Add(row[i] + " ");
              
                              }
                          }
                      }
              
                      private static DataTable dataTable()
                      {
                          DataTable table = new DataTable();
                          DataColumn idColumn = table.Columns.Add("ID", typeof(int));
                          table.Columns.Add("Name", typeof(string));
                          table.PrimaryKey = new DataColumn[] { idColumn };
                          table.Rows.Add(new object[] { 1, "TheScripts" });
                          table.Rows.Add(new object[] { 2, ".Net" });
                          table.Rows.Add(new object[] { 3, "Programmingr" });
                          table.Rows.Add(new object[] { 4, "Fun" });
                          table.AcceptChanges();
                          return table;
                      }
                  }
              }
              Atran.

              Comment

              • Atran
                Contributor
                • May 2007
                • 319

                #8
                Originally posted by lildiapaz
                Thanks for the help Atran. I have been working on this problem the past few days and I'm still stuck. I wrote a function that returns the datatable, but the problem is that I don't know what to write in my listbox double click event to load the tables......... ..
                Can anyone help?
                Hello:
                Try this code:
                Code:
                using System;
                using System.Data;
                using System.Data.SqlClient;
                using System.Windows.Forms;
                
                namespace WindowsApplication
                {
                    public partial class Form1 : Form
                    {
                        DataTable table;
                        ListBox listbox1;
                        Form form;
                        DataTableReader reader;
                        public Form1()
                        {
                            InitializeComponent();
                            form = new Form();
                            form.Show();
                
                            listbox1 = new ListBox();
                            listbox1.Size = new System.Drawing.Size(100, 100);
                            listbox1.Location = new System.Drawing.Point(10, 60);
                            listbox1.DoubleClick += new EventHandler(listbox1_DoubleClick);
                            form.Controls.Add(listbox1);
                        }
                
                        void listbox1_DoubleClick(object sender, EventArgs e)
                        {
                            DoIt();
                        }
                        public void DoIt()
                        {
                            table = new DataTable();
                            reader = new DataTableReader(dataTable());
                            table.Load(reader);
                            foreach (DataRow row in table.Rows)
                            {
                                for (int i = 0; i < table.Columns.Count; i++)
                                {
                                    listbox1.Items.Add(row[i] + " ");
                                }
                            }
                        }
                
                        private static DataTable dataTable()
                        {
                            DataTable table = new DataTable();
                            DataColumn idColumn = table.Columns.Add("ID", typeof(int));
                
                            table.Columns.Add("Name", typeof(string));
                            table.PrimaryKey = new DataColumn[] { idColumn };
                            table.Rows.Add(new object[] { 1, "TheScripts" });
                            table.Rows.Add(new object[] { 2, ".Net" });
                            table.Rows.Add(new object[] { 3, "Programmingr" });
                            table.Rows.Add(new object[] { 4, "Fun" });
                            table.AcceptChanges();
                            return table;
                        }
                    }
                }
                Hope it helped you.

                Comment

                • lildiapaz
                  New Member
                  • Jul 2007
                  • 38

                  #9
                  Hi, Atran
                  I tried to declare the Datatable and the form globally so that I would be able to use it in my application to dynamically create and display the listbox. The problem i'm currently having is by doing so the tables are null, which means they don't return anything or have no value. I'm still having problems on the listbox1 doubleclick event. My application still doesn't display the 2nd listbox with the tables, my code just breaks at a particular line. Any suggestions? I think I'm taking the right approach, I'm just missing something very subtle in my code.

                  here's my code:
                  Code:
                  namespace Project_3
                  {
                      public partial class Form1 : Form
                      {
                          ListBox listbox1;
                          ListBox listbox2;  
                          Form form=new Form();
                          public Form1()
                          {
                              InitializeComponent();
                          }
                  
                          private void label1_Click(object sender, EventArgs e)
                          {
                  
                          }
                  
                          private void textBox1_TextChanged(object sender, EventArgs e)
                          {
                  
                          }
                  
                   private void button1_Click(object sender, EventArgs e)
                          {  
                  get_db_tables();
                  }
                  public DataTable get_db_tables()
                          {
                              //get databases
                              Label labels = new Label();
                              labels.Location = new System.Drawing.Point(10, 35);
                              labels.Text = "Select a database";
                               listbox1 = new ListBox();
                              listbox1.Size = new System.Drawing.Size(100, 100);
                              listbox1.Location = new System.Drawing.Point(10, 60);
                              listbox1.DoubleClick += new System.EventHandler(this.listBox1_DoubleClick);
                             DataTable database = dbConnect("HPMS3 ", "Databases");//myConnection.GetSchema("Databases");
                              foreach (DataRow row in database.Rows)
                              {             
                                  // if (row.ItemArray[0].ToString() == "HPMS3")
                                  // {
                                 // for(int count=0; count<
                                  listbox1.Items.Add(row["database_name"]);
                                  //}
                              }
                              //Form form = new Form();
                              form.Controls.Add(listbox1);
                              form.Controls.Add(labels);
                              form.Show();           
                              return database;
                          }
                  
                  private void listBox1_DoubleClick(object sender, EventArgs e)
                          {
                  
                              Tables();
                          }
                          public void Tables()
                          {
                              // get tables
                              listbox2 = new ListBox();
                              listbox2.Size = new System.Drawing.Size(140, 100);
                              listbox2.Location = new System.Drawing.Point(150, 60);
                              listbox2.Visible = false;
                              //   string[] restrictions = new string[4];
                              //  restrictions[0] = "HPMS3";
                              DataTable database=new DataTable();
                             DataTable tables=new DataTable();
                             tables = dbConnect("", "Tables"); //myConnection.GetSchema("Tables", restrictions);
                              foreach (DataRow rowTable in tables.Rows)
                              {
                                  for (int i = 0; i < database.Columns.Count; i++)
                                  {
                                      listbox2.Items.Add(rowTable[i].ToString());
                                  }
                              }
                              Label label2 = new Label();
                              label2.Location = new System.Drawing.Point(140, 35);
                              label2.Text = "Select table";
                             form.Controls.Add(listbox2);
                              form.Controls.Add(label2);            
                              form.Show(listbox2);
                              listbox2.Visible = true;
                          }
                          private DataTable dbConnect(string dbase, string schema)
                          {
                              SqlConnection myConnection = new SqlConnection();
                              DataTable table = null;
                  
                              myConnection.ConnectionString = "Data Source=ipaddress, 1433; Network library=DBMSSOCN; Initial Catalog=" + dbase + ";User=user;Password=password ";
                              SqlCommand thisCommand = myConnection.CreateCommand();
                              try
                              {
                                  myConnection.Open();
                                  textBox1.Text = "Connected!";
                                  table = myConnection.GetSchema(schema);
                              }
                              catch (Exception ex)
                              {
                                  MessageBox.Show(ex.Message);
                                  MessageBox.Show(ex.StackTrace);
                                  MessageBox.Show("Failed to connect!");
                                  MessageBox.Show("Could not connect to database, please try again!");
                                  Application.Restart();
                                  //throw(ex);
                  
                                  // create dataset to hold rows, columns, etc
                                  // DataSet dataset = new DataSet();
                              }
                              finally
                              {
                                  if (myConnection != null)
                                      myConnection.Close();
                              }
                              return table;

                  Comment

                  • programming
                    New Member
                    • Nov 2008
                    • 3

                    #10
                    questions

                    hi, i saw your codings. And i wish to ask about one thing.

                    Is it possbile to put the connection data inside web method rather than putting here.

                    can help ?

                    Comment

                    Working...