2011-12-28 74 views
2

我在繩子的一端創建的DataGridView ...在運行時

我正在從dateTimePicker的價值,我根據來自dateTimePicker的值執行一個SQL查詢。查詢的結果應該在執行查詢後顯示在Datagridview上。

這是迄今爲止我所做的代碼:

namespace App1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

      DateTime varDate; 
      varDate = dateTimePicker1.Value; 
       } 


     private void button1_Click(object sender, EventArgs e) 
     { 
      SqlConnection con = new SqlConnection(@"Data Source=SUBASH-LAPTOP\COBRA;Initial Catalog=Test;Integrated Security=True"); 

      SqlCommand Command = con.CreateCommand(); 

      Command.CommandText = "Select * From orders where date_purchased <= @varDate "; 

      con.Open(); 

      SqlDataReader reader = Command.ExecuteReader(); 

      DataSet ds = new DataSet(); 
      DataTable dt = ds.Tables.Add(); 
      DataGridView d1 = new DataGridView(); 
      this.Controls.Add(d1); 
      while (reader.Read()) 
      { 
       d1.DataSource = ds.Tables[0]; 

     }  

    } 
} 

我用C#很缺乏經驗,所以任何答案會很感激。

請幫忙。

感謝,

Subash

回答

2

使用此代碼:

private void button1_Click(object sender, EventArgs e) 
{ 

    SqlConnection con = new SqlConnection(@"Data Source=SUBASH-LAPTOP\COBRA;Initial Catalog=Test;Integrated Security=True"); 

    SqlCommand Command = con.CreateCommand(); 

    SqlDataAdapter dp = new SqlDataAdapter("Select * From orders where date_purchased <= @varDate", con); 
    dp.SelectCommand.Parameters.AddWithValue("@varDate", dateTimePicker1.Value); 
    DataSet ds = new DataSet(); 
    dp.Fill(ds); 
    DataGridView d1 = new DataGridView(); 
    d1.DataSource = ds; 
    d1.DataMember = ds.Tables[0].TableName; 
    this.Controls.Add(d1); 

}  
1

您必須將參數添加到SqlCommand它使用:parmeter值

Command.Parameters.AddWithValue("@varDate", DateTimePicker1.Value); 
1

,因爲我看到你的代碼,你缺少分配,

Command.CommandText = "Select * From orders where date_purchased <= @varDate "; 

此行後你必須提供參數值e命令對象。

Command.Parameters.AddWithValue("@varDate", DateTimePicker1.Value); 
2

看看下面的鏈接:

How to: Bind Data to the Windows Forms DataGridView Control

DataGridView的對象將數據從「綁定源」讀你有鏈接到包含您的SQL SELECT語句的TableAdapter。

你大概是那裏的一半。讓連接字符串正常工作是戰鬥的一半。另一半是找出你的數據與DatagridView的關係。

好運!

+0

感謝您的鏈接有...它幫助了我很多 – Subash 2011-12-28 17:23:50

+0

如果你喜歡的答案;請將其投票,以便其他人也可以看到鏈接! – DevinBM 2011-12-30 16:30:35