错误提示“ConnectionString属性尚未初始化”.在c#
本文关键字:初始化 提示 ConnectionString 属性 错误 | 更新日期: 2023-09-27 18:17:05
这段代码是用于组合框的,我想在其中选择一些索引以显示给我的文本框。
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
cmd.Connection = conn;
string query = "SELECT * FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'";
db.connectDB();
db.da.SelectCommand = new OleDbCommand(query, db.conn);
db.executeQryCommand(query, false);
maxRecord = db.ds.Tables[0].Rows.Count;
loadRecords(recordCounter);
cmd.CommandText = query;
dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr["Gname"].ToString();
textBox2.Text = dr["Gcontactno"].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}
//我的程序正在完全运行,但不在这个部分。(
您是否使用conn对象在应用程序和数据库源之间建立了连接?您可以使用conn对象作为连接对象,但在此之前,您初始化了connection ?简单地使用like
"SqlConnection conn=new SqlConnection("Connection_Source");"
您必须为连接定义连接字符串,这里我建议您执行命令的最佳方法。
using (OleDbConnection conn = new OleDbConnection("yourconnectionString"))
{
conn.Open();
using (OleDbCommand cmd =new OleDbCommand("your query text", conn))
{
// execute your command
}
}
如果只是从comboBox中选择值并显示在textBox中,那么下面的代码将帮助您…
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT Gname,Gcontactno FROM GuestInfo WHERE Groomno= '" + comboBox2.Text + "'", conn);
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
textBox1.Text = dr[0].ToString();
textBox2.Text = dr[1].ToString();
}
conn.Close();
}
catch (Exception er)
{
MessageBox.Show("Error! " + er.Message);
}
}