c# - 在 C# 中,如何在 SQL Server 中查找表的列名?

标签 c# sql-server ado.net

我可以在列表框中查找并显示所有表的所有名称。

但我需要通过单击按钮显示列表框中所选表格的列名。

我的功能:

public void GetTableNames()
{
    string strConnect = "Data Source=;Initial Catalog=DATA;User ID=sa;Password=***";
    using (SqlConnection con = new SqlConnection(strConnect))
    {
        con.Open();

        using (SqlCommand com = new SqlCommand(@"SELECT * FROM INFORMATION_SCHEMA.TABLES
                                                 WHERE TABLE_TYPE='BASE TABLE'  
                                                 ORDER BY TABLE_NAME ASC ", con))
        {
            using (SqlDataReader reader = com.ExecuteReader())
            {
                listBox2.Items.Clear();
                int counter = 0;
                while (reader.Read())
                {
                    counter++;
                    listBox2.Items.Add((string)reader["TABLE_NAME"]);
                }

                lblTablesCount.Text = counter.ToString();
            }
        }
    }
}

调用按钮中的函数

private void button1_Click(object sender, EventArgs e)     
{
    GetTableNames();
}

我的问题:给定一个选定的表,我如何找到该表的列的名称?用户从列表框中选择该表并单击一个按钮。

最佳答案

只需在 INFORMATION_SCHEMA.COLUMNS 中搜索

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @yourtablename




public List<string> GetColumnNames(string tableName)
{
    List<string> columns = new List<string>();
    string strConnect = ".........";
    using (SqlConnection con = new SqlConnection(strConnect))
    {
         con.Open();
         using (SqlCommand com = new SqlCommand(@"SELECT COLUMN_NAME 
                                 FROM INFORMATION_SCHEMA.COLUMNS 
                                 WHERE TABLE_NAME = @yourtablename", con))
         {

             com.Parameters.AddWithValue("@yourtableName", tableName);
             using (SqlDataReader reader = com.ExecuteReader())
             {
                 columns.Add(reader["COLUMN_NAME"].ToString());
             }
         }
    }
    return columns;
}

现在,在调用方法中将返回的列列表添加到您的用户界面对象中以供显示

private void button2_Click(object sender, EventArgs e)
{
     string tableName = comboBox1WithTable.SelectedItem.ToString();
     List<string> cols = GetColumnNames(tableName);
     comboBox2WithColumns.DataSource = cols;
}

关于c# - 在 C# 中,如何在 SQL Server 中查找表的列名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21638750/

相关文章:

c# - 异步 Json.net 反序列化

c# - 有没有办法在 IIS6 中访问 asp.net Response.Headers?

c# - 如何正确捕获调用存储过程的返回值

asp.net - 主键违规约束

c# - 下拉列表重置

c# - Git 无法区分或 merge utf-16 编码的 .cs 文件

SQL在本地和远程服务器之间同步数据库

SQL - 为每条记录调用存储过程

entity-framework - ADO.Net 实体模型 (edmx) 与 Entity Framework (v4.0 等)

c# - 如何处理 DALC 中的非必填文件上传字段?