2017-06-09 50 views
-2

我已經使用Visual Studio上的c#編寫了一個簡單的用戶登錄程序,它從Access數據庫中提取數據。我如何才能在登錄新窗口窗體時顯示用戶的信息(例如姓名,地址等)。如何根據用戶登錄將數據讀寫到訪問數據庫?

謝謝, 下面是我目前的代碼。

public partial class Form1 : Form 
{ 
    private OleDbConnection con = new OleDbConnection(); 

    public Form1() 
    { 
     InitializeComponent(); 
     con.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\John\Documents\Visual Studio 2015\Projects\Users.accdb; 
           Persist Security Info=False;"; 
    } 


    private void button1_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      con.Open(); 
      OleDbCommand command = new OleDbCommand(); 
      command.Connection = con; 
      command.CommandText = "select * from employees where SiteName= '" + siteNameComboBox.Text + "' and Lawson= '" + pinText.Text + "'"; 
      OleDbDataReader reader = command.ExecuteReader(); 
      int count = 0; 
      while (reader.Read()) 
      { 
       count = count + 1; 
      } 

      if (count == 1) 
      { 
       MessageBox.Show(" Username and password correct!"); 

       this.Hide(); 
       Main frm2 = new Main(); 
       frm2.ShowDialog(); 
      } 
      else if (count > 1) 
      { 
       MessageBox.Show("Duplicate username and password found!"); 
      } 
      else 
      { 
       MessageBox.Show("Username and Password is not correct"); 
      } 

      con.Close(); 
+0

你可以使用它在整個應用程序範圍的全局變量。登錄時設置這些變量的值。如果您正在使用MDI表單,則可以以這種形式聲明這些變量。 – Srikanth

+0

你好,請你澄清一下你是什麼**完全**試圖實現?數據庫的模式結構是什麼?你在問如何檢索這些信息,或者如何在表單上顯示它?到目前爲止,你完全嘗試了什麼?你有沒有跟着任何教程學習如何處理這個/研究的最佳實踐?如果您的問題更具體,幷包含儘可能多的信息,我們將能夠更有效地幫助您。 – Clint

+0

我正在構建一個程序,用戶可以使用用戶名和密碼登錄。登錄後,會打開一個新表單並顯示其信息。如姓名,地址等(全部在數據庫文件中)。是否可以將其「名稱」設置爲表單上的label.text?這僅用於教育目的,因爲我正在嘗試學習C# –

回答

0

這是我爲我的項目做的一個示例代碼。您可能需要根據您的規範和數據結構更改一些代碼。如有任何疑問或疑問,請在評論中告知我。

更新版本

class bankAccount 
{ 
    string acNo; 
    string acName; 
    string bank; 
    string acType; 
    frmShowAccount form=new frmShowAccount(); 

    public void viewAccount(string acNo) 
    { 
     this.acNo = acNo; 

     using (SqlConnection newCon = new SqlConnection(db.GetConnectionString)) 
     { 
      SqlCommand newCmd = new SqlCommand("SELECT Employee.Name, BankAccount.ac_name, BankAccount.bank_name, BankAccount.ac_type FROM BankAccount INNER JOIN Employee ON BankAccount.emp_id = Employee.Emp_ID WHERE (BankAccount.ac_no = @bankAccount)", newCon); 

      newCmd.Parameters.Add("@bankAccount", SqlDbType.Char).Value = acNo; 
      newCon.Open(); 
      SqlDataReader rdr = newCmd.ExecuteReader(); 
      rdr.Read(); 

      // Setting values to the text boxes in the current instance of form 
      form.txtName.text=rdr[0]; 
      form.txtACName.text=rdr[1]; 
      form.txtBankName.text=rdr[2]; 
      form.txtACType.text=rdr[3];   
     } 
    } 
} 

//CALLING THE ABOVE METHOD 
bankAccount newBA = new bankAccount(); 
newBA.form.this; // reference 'form' which is in the 'bankAccount' class is 
//set to current instance of the form object. 
相關問題