2011-03-25 275 views
0

我已閱讀關於此問題的其他問題,但沒有看到我的代碼拋出此錯誤的位置或原因。我的代碼如下,如果任何人都可以看到我要去哪裏錯了。C#錯誤'對象引用未設置爲對象的實例'

private void btnSignIn_Click(object sender, EventArgs e) 
    { 
     sqlConnectionNW.ConnectionString = "Data Source=" + server + ";Initial Catalog=Northwind;Integrated Security=True"; 
     try 
     { 
      sqlConnectionNW.Open(); 
      String enteredDate = cmbDay.SelectedItem.ToString() + "/" + cmbMonth.SelectedItem.ToString() + "/" + cmbYear.SelectedItem.ToString(); 

      if ((txtEmployeeID.TextLength != 0) && (enteredDate.Length != 0)) 
      { 
       int ID = Convert.ToInt32(txtEmployeeID.Text); 
       employeesBindingSource.Filter = "EmployeeID ='" + txtEmployeeID.Text + "'"; 
       String birthDate; 
       birthDate = dsEmployees.Employees.FindByEmployeeID(ID).BirthDate.ToShortDateString(); 

       if (employeesBindingSource.Count > 0) //GETS TO HERE AND THEN GOES TO CATCH EX 
       { 
        sqlConnectionNW.Close(); 
        if (enteredDate.ToString() == birthDate.ToString()) 
        { 
         frmMenu frmMainMenu = new frmMenu(); 
         frmMainMenu.server = server; 
         frmMainMenu.employeeID = txtEmployeeID.Text; 
         MessageBox.Show("Welcome to the Northwind Ordering System"); 
         this.Hide(); 
         frmMainMenu.Show(); 
        } 
        else 
        { 
         MessageBox.Show("The birth date you have entered is incorrect"); 
        } 
       } 
       else 
       { 
        MessageBox.Show("The Employee ID you have entered does not exist"); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     sqlConnectionNW.Close(); 
    } 
+7

你可以發佈堆棧跟蹤嗎?你知道哪一行是拋出錯誤嗎? – Andy 2011-03-25 01:16:52

+1

@Jon,編譯器如何幫助找到運行時異常的原因? – 2011-03-25 01:19:27

+0

已編輯帖子以顯示發生錯誤的位置。 – 6TTW014 2011-03-25 01:21:25

回答

1

管理解決這個問題。我改變了這一點:

if ((txtEmployeeID.TextLength != 0) && (enteredDate.Length != 0)) 
      { 

       int ID = Convert.ToInt32(txtEmployeeID.Text); 

       employeesBindingSource.Filter = "EmployeeID ='" + txtEmployeeID.Text + "'"; 

       String birthDate; 

       birthDate = dsEmployees.Employees.FindByEmployeeID(ID).BirthDate.ToShortDateString(); // FROM HERE 

       if (employeesBindingSource.Count != 0) 
       { 

        sqlConnectionNW.Close(); 

要這樣:

IF((txtEmployeeID.TextLength = 0)& &(enteredDate.Length = 0)!) {

   int ID = Convert.ToInt32(txtEmployeeID.Text); 

       employeesBindingSource.Filter = "EmployeeID ='" + txtEmployeeID.Text + "'"; 

       String birthDate; 

       if (employeesBindingSource.Count != 0) 
       { 
        birthDate = dsEmployees.Employees.FindByEmployeeID(ID).BirthDate.ToShortDateString(); //TO HERE 

        sqlConnectionNW.Close(); 

這是隻是在if語句之後放置「birthDate = ...」的情況。

相關問題