C#如何将数据从数据库获取到文本框
本文关键字:获取 文本 数据库 数据 | 更新日期: 2023-09-27 18:08:31
问候程序员
我在windows窗体中有一个组合框和一些文本框,它们连接到一个数据库。我的想法是,当组合框的值发生变化时,文本框中的数据也会发生变化。就像我在组合框中选择客户ID时,文本框将加载客户的数据,如全名或地址等。但当我打开表单时,组合框将消失,文本框保持为空。我正在使用Access数据库和Visual Studio 2012进行编码。这是我的密码。。
C#代码:
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
string pc = Convert.ToString(comboBox1.SelectedValue);
string sql = "SELECT * FROM Customer WHERE CustomerID="+ pc;
Data.Customer_Data(sql, pc);
txtfullname.Text = Data.fullname;
txtadress.Text = Data.adress;
txtcity.Text = Data.city;
txtemail.Text = Data.email;
}
我的课叫数据:
public static string cs = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "''Database1.accdb";
public static string fullname = "";
public static string adress = "";
public static string city = "";
public static string email = "";
public static void Customer_Data(string sql, string pc)
{
if (pc == "")
{
return;
}
else
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(cs);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand(sql,oleDbConnection1);
OleDbDataReader reader = oleDbCommand1.ExecuteReader();
if (!reader.Read())
return;
fullname = reader["fullname"].ToString();
adress = reader["adress"].ToString();
city = reader["city"].ToString();
email = reader["email"].ToString();
oleDbConnection1.Close();
}
}
您可以尝试以下调试技术之一,看看会发生什么。
- 在行
Data.Customer_Data(sql, pc);
之后,属性的数据是否正确加载 - 您还可以检查是否有传递的相应客户id的数据库值吗?使得不执行该条件CCD_ 2
- 检查一下页面加载方法(我相信它不会影响组合框的可见性,但嘿,尝试一下没有害处(
如果这里提到的都不起作用,那么更多的代码可能会有所帮助。