Newbiee
Newbiee

Reputation: 43

Fill Combobox with Tables in database c#

How do I fill the combobox with tables (not columns in specific table) in database.

I already did something common like "Data Bound", but when I ran/debug the system, nothing appears in combobox.

Here's my code:

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            SqlConnection connection = new SqlConnection(@"Data Source=USER-PC;Initial Catalog=StudentDB;Integrated Security=True");

            string selectQuery = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'";
            connection.Open();
            SqlCommand command = new SqlCommand(selectQuery, connection);
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                comboBox1.Items.Add(reader.GetString("tables"));
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

Any help from experienced developers out there?

Upvotes: 0

Views: 57

Answers (1)

SyMo7amed
SyMo7amed

Reputation: 378

the column name is wrong in your code, READER["tables"], the correct column name is TABLE_NAME, try the code below :

using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand com = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES", con))
    {
    using (SqlDataReader reader = com.ExecuteReader())
        {
        myComboBox.Items.Clear();
        while (reader.Read())
            {
            myComboBox.Items.Add((string) reader["TABLE_NAME"]);
            }
        }
    }
}

Upvotes: 1

Related Questions