簡體   English   中英

使用DataGridView從數據庫表中檢索數據

[英]Retrieving Data from a database table using DataGridView

這是我的代碼:

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窗體應用程序,我將在其中輸入開始日期時間和結束日期時間以在表中顯示結果,但是每當我運行時,都會出現以下錯誤:我正在使用Visual Studio 2015。 僅當我直接在查詢中使用日期時間而不是文本框時才有效

錯誤:“ System.Data.dll中發生了'System.Data.SqlClient.SqlException類型的未處理的異常。附加信息:從字符串轉換日期和/或時間時轉換失敗。”

我認為問題是您在數據庫中對變量的定義應該是nvarchar()而不是char()。 在代碼中使用一個斷點來找出您的文本框值是否加上一些空格

首先,查詢中的語法不正確: Enter_Exit_Time >='textboxValue1' AND Enter_Exit_Time <='textboxValue2' ,您在查詢中發送了textboxValue的名稱而不是其值。

由於您嘗試將文本發送到SQL無法DateTime字段(根據錯誤消息),因此會產生錯誤。

我建議您使用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM