2013-04-10 178 views
0

问候程序员,C#我如何从数据库中获取数据,文本框

我有一个组合框,在我的Windows中的一些文本框状地连接到一个数据库。我的想法是,当组合框的值改变文本框中的数据时也会发生变化。就像当我在组合框中选择客户ID时,文本框将加载客户的数据,例如全名或地址等。但是,当我打开表单时,组合框disapear和文本框保持空白。我正在使用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(); 
      } 
    } 
+0

W00t comboBox disapears?你有没有将comboBox属性设置为false? – Obama 2013-04-10 11:38:17

+0

你在form_Load事件中有什么代码? – StackTrace 2013-04-10 11:45:50

+0

不,它只是消失 – user2241062 2013-04-10 11:46:09

回答

-1

你可以尝试以下的调试技术之一,看看发生了什么。

  1. 在此行之后Data.Customer_Data(sql, pc);是否正确加载属性的数据?
  2. 你还可以检查是否有相应的客户ID传递的数据库值?所以这个条件if (!reader.Read()) return;不被执行。
  3. 检查你的页面加载方法(我相信它不能与组合框的可见性一起玩,但嘿,试试没有什么坏处)。

如果这里没有提到这些工作,那么可能会有更多的代码会有所帮助。

+0

分别尝试阅读器[0]而不是阅读器[“全名”]和阅读器[1]阅读器[“地址”]。 – 2013-04-10 11:54:47

+0

同时检查这个类的静态变量是否搞乱了某些东西。 – 2013-04-10 11:57:17

+0

我发现这个问题,它的数据库,另一个表名中有一个空格.. Visual Studio不是这样的..感谢anwser反正 – user2241062 2013-04-10 12:10:31

相关问题