C# 获取 SQL 表列名并排序添加到下拉框
以下是一个示例代码,可以访问 SQL 查询表中的全部列名,并将它们排序并添加到下拉框的显示中:
string connectionString = 'Your Connection String Here';
string tableName = 'Your Table Name Here';
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Get the column names from the table
DataTable schemaTable = connection.GetSchema('Columns', new string[] { null, null, tableName });
List<string> columnNames = new List<string>();
// Loop through the rows in the schema table to get the column names
foreach (DataRow row in schemaTable.Rows)
{
string columnName = (string)row['COLUMN_NAME'];
columnNames.Add(columnName);
}
// Sort the column names alphabetically
columnNames.Sort();
// Add the column names to the dropdown list
foreach (string columnName in columnNames)
{
comboBox1.Items.Add(columnName);
}
}
请注意,此代码中的 'comboBox1' 是您要将列名添加到的 ComboBox 控件的名称。您需要将 'Your Connection String Here' 和 'Your Table Name Here' 替换为您自己的连接字符串和表名。
原文地址: https://www.cveoy.top/t/topic/mHXb 著作权归作者所有。请勿转载和采集!