C#如何从数据库获取数据到文本框

时间:2013-04-10 11:25:55

标签: c# database combobox oledb

问候程序员,

我有一个组合框,我的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;

    }

我的班级名为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();
            }
    }

1 个答案:

答案 0 :(得分:-1)

您可以尝试以下调试技巧之一,看看发生了什么。

  1. 在此行Data.Customer_Data(sql, pc);之后,属性的数据是否正确加载?
  2. 您是否还可以检查相应的客户ID是否有数据库值?这样就不会执行这个条件if (!reader.Read()) return;
  3. 检查您的页面加载方法(我确定它不会与组合框的可见性一起玩,但是嘿,尝试没有任何害处。)
  4. 如果这里没有提到任何工作,那么可能会有更多代码帮助。