2012-11-26 26 views
1

我有一個小問題就在這裏: 我有一個組合框,在數據庫中獲取從列的值,我用它來背輸入數據到另一個。安迪在數據庫 像如何在C#中執行SQL SELECT語句

comboBox2.DataSource = ds1.Tables[0]; 
comboBox2.DisplayMember = "DoctorName"; 
comboBox2.ValueMember = "DoctorCode"; 
comboBox2.BindingContext = this.BindingContext; 

這填補組合框與醫生的名字和值將成爲醫生 的代碼,然後

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=c:\users\administrator\documents\visual studio 2010\Projects\Clinic\Clinic\Clinc.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); 
     con.Open(); 
     SqlCommand cmd1 = new SqlCommand("SELECT Doctors.DoctorCode, Doctors.DoctorName, SessionReservations.SessionCode, SessionReservations.PatientCode, SessionReservations.ExaminationCode, SessionReservations.DoctorCode AS Expr1, SessionReservations.SessionMonth, SessionReservations.SessionYear FROM Doctors INNER JOIN SessionReservations ON Doctors.DoctorCode = SessionReservations.DoctorCode WHERE (Doctors.DoctorCode = @DoctorCode) AND (SessionReservations.SessionMonth = @month) AND (SessionReservations.SessionYear = @year)", con); 
     SqlDataAdapter da2 = new SqlDataAdapter(cmd1); 
     DataSet ds2 = new DataSet(); 

     try 
     { 

      da2.InsertCommand.Parameters.Add("@DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue); 
      da2.InsertCommand.Parameters.Add("@month", SqlDbType.Int).Value = comboBox1.SelectedValue; 
      da2.InsertCommand.Parameters.Add("@year", SqlDbType.Int).Value = textBox2.Text; 

      da2.Fill(ds2); 
      cmd1.ExecuteReader(); 
      con.Close(); 
} 

該代碼可用於選擇特定的行和選擇statment工作就在SQL管理器 但在運行它給錯誤

「System.NullReferenceException:對象引用未設置爲對象的 實例。在 Clinic.DoctorMoneyCall.button1_Click(對象發件人,EventArgs e)如 C:\用戶\管理員\文件\視覺工作室 2010 \項目\診所\診所\ DoctorMoneyCall.cs:行45"

我只是不明白這是怎麼回事錯

+5

哪個是45行? –

+0

@fenonoga - 這只是一個空引用問題。這不是運行SQL查詢所特有的。 –

+0

嘗試調試,並查看您的複選框和文本框是否有任何值作爲參數 –

回答

2

看起來你正在嘗試運行一個select命令,但是你正在將參數添加到insert命令。

 da2.SelectCommand.Parameters.Add("@DoctorCode", SqlDbType.Int).Value = Convert.ToInt32(comboBox2.SelectedValue); 
     da2.SelectCommand.Parameters.Add("@month", SqlDbType.Int).Value = comboBox1.SelectedValue; 
     da2.SelectCommand.Parameters.Add("@year", SqlDbType.Int).Value = textBox2.Text; 
+0

是的,我想每次都選擇不同的東西,所以我必須在查詢語句 –

+0

中創建變量,但是您將它們添加到插入命令,而不是選擇命令。 SQL命令有4種狀態:選擇,更新,插入,刪除。它來自您可以運行的SQL查詢。我將你的「insertcommand」改爲「selectCommand」的 – gashach

+0

噢,我的上帝啊,非常感謝你,我覺得自己很愚蠢,試圖在幾天之內知道錯誤在哪裏,非常愚蠢的事情,我必須再次關注 謝謝 –

0

錯誤消息意味着你使用的對象之一是零。是CON對象正確初始化?

+0

是的連接工作正常,我已經在標籤中顯示了我的文本框和組合框的值,以確保它們正常工作,並且它們的確如此 –

0

好像你傳遞一個變量是空的該文件的第45行,確保所有的值都是非空的

+0

這並沒有太大的意義。他傳遞的內容不能爲null,因爲它的表單上存在的控件的內容和這兩個值都有默認值。 –