使用DataGridView从数据库表中检索数据

时间:2016-05-08 17:19:28

标签: c# winforms

这是我的代码:

Properties.Settings.Default.In_OutConnectionString

c.Open();
// 2
// Create new DataAdapter
string textboxValue1 = textBox1.Text.Trim();
string textboxValue2 = textBox2.Text.Trim();
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM People_Tracking WHERE Enter_Exit_Time >='textboxValue1' AND Enter_Exit_Time <='textboxValue2'", c))
{
    // 3
    // Use DataAdapter to fill DataTable
    DataTable t = new DataTable();
    a.Fill(t);
    // 4
    // Render data onto the screen
    dataGridView1.DataSource = t;
}

我有一个Windows窗体应用程序,我将在其中输入start-date-time和end-date-time以在表中显示结果,但是    无论何时我跑,我都有以下错误:我正在使用visual studio    2015年。它只有在我直接在查询中使用日期时才有效    而不是文本框

  

错误:“System.Data.dll中发生了'System.Data.SqlClient.SqlException'类型的未处理异常          附加信息:   从字符串转换日期和/或时间时转换失败。“

2 个答案:

答案 0 :(得分:1)

我认为问题是你在数据库中定义了你的变量 它应该是nvarchar()而不是char()。 在代码中使用断点来查明文本框值是否加上某个空格

答案 1 :(得分:1)

首先,您的查询语法不正确:Enter_Exit_Time >='textboxValue1' AND Enter_Exit_Time <='textboxValue2',您在查询中发送textboxValue的名称而不是其值。

它会生成错误,因为您尝试将文本发送到DateTime字段 SQL不理解(根据错误消息)。

我建议您使用Parameter来使用SqlDbType.DateTime,然后将DateTime直接传递给参数,同时避免SQL注入,如下所示:

c.Open();
DateTime startDateTime = Convert.ToDateTime(textBox1.Text);
DateTime endDateTime = Convert.ToDateTime(textBox2.Text);
string query = "SELECT * FROM People_Tracking WHERE Enter_Exit_Time BETWEEN @startDateTime AND @endDateTime ;";
SqlCommand cmd = new SqlCommand(query, c);
cmd.Parameters.Add("@startDateTime", SqlDbType.DateTime).Value = startDateTime;
cmd.Parameters.Add("@endDateTime", SqlDbType.DateTime).Value = endDateTime;
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
adapter.Fill(t);
dataGridView1.DataSource = t;
相关问题