2017-06-13 91 views
0

我是C#編程語言的新手。我有問題如何檢查圖像是否存在或不在數據庫中?我正在使用數據庫內部連接。我目前的代碼是工作。但是,如果圖像不存在於數據庫中,則所有文本框都不會從數據庫獲取值。我不想那樣。我想這樣>如果圖像不存在,即使圖像不存在,所有的文本框都從數據庫中獲得了它們的值。請有人幫助我。這裏是我的代碼:檢查數據庫中是否存在圖像C#windows窗體

private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e) 
     { 
      if (e.KeyCode == Keys.Enter) 
      { 
       if (textBoxEmplNo.Text != "") 
       { 

        string selectSql = "select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path from m_employee a inner join m_emp_photo b on b.empno=a.empno where a.empno= @empno"; 

        SqlCommand cmd = new SqlCommand(selectSql, con); 

        cmd.Parameters.AddWithValue("@empno", textBoxEmplNo.Text); 

        bool isDataFound = false; 

        try 
        { 

         con.Open(); 

         using (SqlDataReader read = cmd.ExecuteReader()) 
         { 
          while (read.Read()) 
          { 
           isDataFound = true; 

           textBoxWorkNo.Text = (read["workno"].ToString()); 
           textBoxName.Text = (read["name"].ToString()); 
           textBoxICPass.Text = (read["icnum"].ToString()); 
           textBoxPassport.Text = (read["passport"].ToString()); 
           textBoxDept.Text = (read["deptno"].ToString()); 
           textBoxSection.Text = (read["section"].ToString()); 
           textBoxDesignation.Text = (read["designation"].ToString()); 

           pictureBox1.Visible = true; 
           pictureBox1.Image = Image.FromFile("" + read["path"].ToString()); 

           dataGridView1.Visible = false; 
          } 
         } 

         if (!isDataFound) 
         { 
          textBoxEmplNo.Text = ""; 
          textBoxWorkNo.Text = ""; 
          textBoxName.Text = ""; 

          // Display message here that no values found 
          MessageBox.Show("No Result Found"); 

         } 
        } 
        finally 
        { 


         con.Close(); 
        } 

       } 

       else 
       { 
        textBoxWorkNo.Text = ""; 
        textBoxName.Text = ""; 
       } 

        dataGridView1.Visible = false; 

      } 
     } 
+1

您想顯示來自'm_employee'的員工數據,而不管照片表中的數據是否正確?爲此,只需使用「左連接」。 –

+0

@CoderofCode嗨,我已經試過了。但是如果圖像沒有在數據庫中,它仍然會顯示消息「No Result Found」。我希望員工數據仍然顯示在所有文本框中,即使圖像不存在於數據庫中。你能用代碼解釋更多細節嗎?因爲我在編程方面還是新手。 :( – Miza

+0

我已經爲此寫了答案,請查看 –

回答

0

從我的理解,你想,不論目前不在數據庫中他的照片中顯示的員工數據,以便做表的left join使您的查詢如下變化,

select a.name, a.empno, a.workno, a.icnum, a.passport, a.deptno, a.section, a.designation, b.path 
from 
    m_employee a left join m_emp_photo b 
    on b.empno=a.empno 
where 
    a.empno= @empno 

這將爲您提供左側表中給定員工編號的所有記錄,如果右側表格中沒有可用的值NULL,則從右側進行匹配。

儘管您需要在代碼中處理b.PathNULL值。

所以在這個代碼的代碼行之前,

pictureBox1.Image = Image.FromFile("" + read["path"].ToString()); 

檢查,如果pathDBNULL或不與System.DBNull.Value比較。