2011-04-26 51 views
0

日期文本框的文本框 在寫日期時,在文本框中兩個日期之間的Corrs的數據來自於數據網格 * 我的代碼是: *數據:在代碼中的錯誤

private void btnSubmit_Click(object sender, EventArgs e) 
    { 
     SqlConnection cs = new SqlConnection("Data Source=IRIS-CSG-174;Initial Catalog=library_system;Integrated Security=True"); 
     cs.Open(); 
     SqlCommand cmd = new SqlCommand("select * from dbo.lib_issue_details where book_issue_on between=" + textBox1.Text+""+"and"+ textBox2.Text +"", cs); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 
     DataSet ds = new DataSet(); 
     da.Fill(ds, "lib_issue_details"); 
     dataGridView1.DataBindings.Add(new Binding("text", ds, "lib_issue_details.book_issue_on")); 

它顯示'='附近語法不正確的錯誤。 幫助我在此代碼中...在此先感謝!

回答

3

從查詢
刪除 「=」 應該是where book_issue_on between date1 and date2不需要的 '=' 號

你的代碼應該是

SqlCommand cmd = new SqlCommand("select * from dbo.lib_issue_details where book_issue_on between " + textBox1.Text+""+" and "+ textBox2.Text +"", cs); 

+0

感謝您的答覆,但現在它給錯誤,當我刪除 「=」:的表達在期望條件的上下文中指定的非布爾類型,在'between2011'之間。 – niketa 2011-04-26 07:47:20

+0

您需要在和=號之間的單詞之間有空格。最好的事情是使用參數。 – 2011-04-26 08:13:02

4

我覺得這條線

SqlCommand cmd = new SqlCommand("select * from dbo.lib_issue_details where book_issue_on between=" + textBox1.Text+""+"and"+ textBox2.Text +"", cs);

應該是這樣的:

SqlCommand cmd = new SqlCommand("select * from dbo.lib_issue_details where book_issue_on between " + textBox1.Text + " and " + textBox2.Text, cs);

或者,更好的方法是使用parameters

SqlCommand cmd = new SqlCommand("select * from dbo.lib_issue_details where book_issue_on between @date1 and @date2", cs); 
cmd.Parameters.Add("@date1", SqlDbType.DateTime); 
cmd.Parameters["@date1"].Value = textBox1.Text; 

cmd.Parameters.Add("@date2", SqlDbType.DateTime); 
cmd.Parameters["@date2"].Value = textBox1.Text; 

我可能會考慮使用DateTimePicker而不是文本框。