以下是C#代码示例:

//连接数据库
string connectionString = "Data Source=yourDataSource;Initial Catalog=yourDatabase;User ID=yourUsername;Password=yourPassword;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//查询表格的列名
string tableName = "yourTableName";
string query = string.Format("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{0}'", tableName);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();

//在datagridview中显示列名
dataGridView1.ColumnCount = reader.FieldCount;
for (int i = 0; i < reader.FieldCount; i++)
{
    dataGridView1.Columns[i].Name = reader.GetName(i);
}

//关闭连接
reader.Close();
connection.Close();

注:将代码中的 yourDataSourceyourDatabaseyourUsernameyourPasswordyourTableName 替换为实际的值。

从数据库中读取表格全部的列名并在datagridview中显示

原文地址: https://www.cveoy.top/t/topic/bWgZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录