我正在创建一个链接到数据库的程序。在主窗体上,当用户单击按钮“连接到数据库”时,会加载另一个表单以供用户输入登录详细信息(要连接的服务器,用户名和密码)。但是,由于某种原因,连接无法正常工作。给出的错误是" Fill:SelectCommand.Connection属性尚未初始化。"
到目前为止,这是我的代码:
public void connectDB_Click(object sender, EventArgs e)
{
DatabaseConnection dbConn = new DatabaseConnection();
if (dbConn.ShowDialog() == DialogResult.OK)
{
SqlConnectionStringBuilder connection = new SqlConnectionStringBuilder();
connection.DataSource = DatabaseConnection.dbNameText;
connection.UserID = DatabaseConnection.usernameText;
connection.Password = DatabaseConnection.passwordText;
SqlConnection con = new SqlConnection(connection.ToString());
using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;"))
{
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = command;
DataTable table = new DataTable();
sda.Fill(table);
BindingSource source = new BindingSource();
source.DataSource = table;
dataGridDataBase.DataSource = source;
sda.Update(table);
this.dataGridDataBase.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; //showing data onto the data grid view
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
以上是大师班中的代码;主要形式。以下是登录表单中的代码。
public partial class DatabaseConnection : Form
{
public static string dbNameText;
public static string usernameText;
public static string passwordText;
public bool buttonClicked = false;
public DatabaseConnection()
{
InitializeComponent();
password.PasswordChar = '•';
}
public void connectButton_Click(object sender, EventArgs e)
{
buttonClicked = true;
dbNameText = dbName.Text;
usernameText = username.Text;
passwordText = password.Text;
}
}
请提出任何想法,帮助或解决方案?
答案 0 :(得分:0)
您必须连接命令:
using (SqlCommand command = new SqlCommand("Select name FROM sys.databases;", con))
{
...
}