[英]C# How do I get data from Database to textboxes
問候程序員,
我在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);
屬性的數據是否正確加載? if (!reader.Read()) return;
此條件if (!reader.Read()) return;
不執行。 如果此處沒有提到任何可行的方法,那么可能會有更多代碼會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.