簡體   English   中英

C#如何從數據庫獲取數據到文本框

[英]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();
            }
    }

您可以嘗試以下調試技術之一,然后看看發生了什么。

  1. 此行之后的Data.Customer_Data(sql, pc); 屬性的數據是否正確加載?
  2. 您還可以檢查是否存在傳遞的相應客戶ID的數據庫值? 以便if (!reader.Read()) return;此條件if (!reader.Read()) return; 不執行。
  3. 檢查您的頁面加載方法(我確信它不能與組合框的可見性一起使用,但是嘗試使用此方法沒有任何危害)。

如果此處沒有提到任何可行的方法,那么可能會有更多代碼會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM