0

Now, when the previous issue got resolved, there is a new issue that has risen. When I run my code, it gives me the column name as(which is obviously not my column name):

System.Data.DataRowView

The code that I am using is:

            private void textBox1_TextChanged(object sender, EventArgs e)
        {

                if (textBox1.Text == "select" || textBox1.Text == "SELECT" || textBox1.Text == "SELECT")
                {
                    string cmdstr = @"select * from information_schema.columns where table_name = '" +comboBox1.SelectedItem+ "'"; 
                    string conStr = @"Data Source=INPDDBA027\NGEP;Initial Catalog=Dev_Server;Integrated Security=True";
                    DataTable dt = new DataTable();
                    SqlDataAdapter sda = new SqlDataAdapter(cmdstr, conStr);
                    sda.Fill(dt);
                    listBox2.DataSource = dt;

            }

        }

Please Help.

ankastic
  • 171
  • 2
  • 14

1 Answers1

1

INFORMATION_SCHEMA is your way:

SELECT 
COLUMN_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME = 'YourTableNameHere'

You need to execute this using SqlCommand, and use the result as a dataSource for your ListBox. Like this:

private static List<string> ReadTableColumns(string connectionString)
{
    List<string> columnNames = new List<string>();
    string queryString = 
        "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS " +
      + "WHERE TABLE_NAME = 'YourTableNameHere'";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(
            queryString, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        try
        {
            while (reader.Read())
            {
                columnNames.Add(reader[0].ToString());
            }
        }
        finally
        {
            // Always call Close when done reading.
            reader.Close();
        }
    }

    return ColumnNames;
}


listBox1.Datasource = ReadTableColumns(yourConnectionString);
Zein Makki
  • 29,485
  • 6
  • 52
  • 63