SQL 服务器 - 列名未显示在 C# 中的列表框中

本文关键字:列表 显示 服务器 SQL | 更新日期: 2023-09-27 17:56:56

现在,当上一个问题得到解决时,出现了一个新问题。当我运行代码时,它给了我列名(这显然不是我的列名):

System.Data.DataRowView

我使用的代码是:

            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;
            }
        }

请帮忙。

SQL 服务器 - 列名未显示在 C# 中的列表框中

INFORMATION_SCHEMA是你的方式:

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

您需要使用 SqlCommand 执行此操作,并将结果用作ListBoxdataSource。喜欢这个:

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);