[英]C# How do I get data from Database to textboxes
Greetings programmers, 问候程序员,
I have a combobox and some textboxes in my windows form connected to a database. 我在Windows窗体中有一个组合框和一些文本框连接到数据库。 My idea is, when the value of the combobox changes the data in the textboxes changes too.
我的想法是,当组合框的值更改时,文本框中的数据也会更改。 Like when I pick a customer ID in the combobox, the textboxes will be loaded with the data of the customer, like the Full name or the address etc. But when I open the Form the combobox disapear's and the textboxes stays empty.
就像当我在组合框中选择一个客户ID时,文本框将加载客户的数据,例如全名或地址等。但是当我打开表单时,组合框就会消失并且文本框保持空白。 I am using Access database and Visual Studio 2012 to code.
我正在使用Access数据库和Visual Studio 2012进行编码。 Here is my code..
这是我的代码。
C# code : 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;
}
And my class called Data: 我的课叫做数据:
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();
}
}
You can try one of the following debugging techniques and see what is happening . 您可以尝试以下调试技术之一,然后看看发生了什么。
Data.Customer_Data(sql, pc);
Data.Customer_Data(sql, pc);
does the data for the properties load properly? if (!reader.Read()) return;
if (!reader.Read()) return;
此条件if (!reader.Read()) return;
is not executed. If none of them mentioned here work then may be some more code will help. 如果此处没有提到任何可行的方法,那么可能会有更多代码会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.