简体   繁体   中英

Retrieving Data from a database table using DataGridView

This is my code :

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;
}

I have a windows form application where I will enter start-date-time and end-date-time to show result in table, but whenever I run , I have the error below: I am using visual studio 2015 . It only works if i use the date time directly in the query instead of the text boxs

error: "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Additional information: Conversion failed when converting date and/or time from character string."

I think the problem is your definition of you variable in database it should be nvarchar() instead of char(). Use a break point in you code to find out that your textbox values plus by some space or not

First, your syntax in query is incorrect : Enter_Exit_Time >='textboxValue1' AND Enter_Exit_Time <='textboxValue2' , you send on the query the name of textboxValue instead of its value.

It generates an error because you trying to send a text to a DateTime field that SQL doesn't understand (according to the error message).

I advice you to use the Parameter to use SqlDbType.DateTime and then pass the DateTime directly to the parameter, and also avoid SQL injections , like this :

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM