请问,用C#,连接上数据库后,如何将数据库名称显示在combobox下拉列表内,希望能分享一下代码案例,谢谢;
基于Monster 组和GPT的调写:
示例:
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace DatabaseList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadDatabaseList();
}
private void LoadDatabaseList()
{
string connectionString = "Server=yourServerName;Integrated Security=true";
string query = "SELECT name from sys.databases WHERE name NOT IN ('master', 'tempdb', 'model', 'msdb')";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string dbName = reader.GetString(0);
comboBox1.Items.Add(dbName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
}
定义了一个 LoadDatabaseList 方法,它连接到 SQL Server 数据库并使用 SELECT 查询语句从 sys.databases 系统表中检索所有数据库的名称。在这里,还使用 WHERE 子句过滤了系统数据库,因为不想在 ComboBox 中显示这些数据库。
在读取查询结果时,使用 SqlDataReader 对象来读取数据行,并使用 GetString 方法检索第一列中的数据库名称。然后,将数据库名称添加到 ComboBox 的 Items 集合中。
请注意,你需要根据你的 SQL Server 实例名称和数据库名称更改 connectionString 变量和查询语句中的 yourServerName。你还需要在 Form 中添加一个名为 comboBox1 的 ComboBox 控件。
执行一个查询,
select id,name from sysdatabases
然后绑定DataSoure
手机回答真费劲