我在绳子的尽头......
我从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
答案 0 :(得分:2)
查看以下链接:
How to: Bind Data to the Windows Forms DataGridView Control
DataGridView对象从“绑定源”读取数据,您必须将其链接到包含SQL SELECT语句的TableAdapter。
你的方式大约是1/2。使连接字符串正常工作是成功的一半。另一半是找出数据与DatagridView相关的位置。
祝你好运!答案 1 :(得分: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);
}
答案 2 :(得分:1)
您必须将参数添加到SqlCommand
才能使用它:
Command.Parameters.AddWithValue("@varDate", DateTimePicker1.Value);
答案 3 :(得分:1)
当我看到你的代码时,你缺少参数值的分配,
Command.CommandText = "Select * From orders where date_purchased <= @varDate ";
在此行之后,您必须为命令对象提供参数值。
Command.Parameters.AddWithValue("@varDate", DateTimePicker1.Value);