T
T
Therapyx2015-07-28 16:38:47
SQL
Therapyx, 2015-07-28 16:38:47

How to solve the problem of DateTime envelope when selecting from Gridview?

Such a problem. There is a GridView, a button and a text field. Task: display all records in the GridView from the database by the given date in the test field.

Код по нажатию кнопки:
            DateTime datetime = Convert.ToDateTime(TextBox1.Text);
            SqlCommand cmd = new SqlCommand("Select * from Purchase where P_Date = '" + datetime + "'", cn);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            gvPurchase.DataSourceID = null;
            gvPurchase.DataSource = dt;
            gvPurchase.DataBind();

for the test, I also created a label, if I enter a date in TextBox1, then the label shows "07/17/2015 00:00:00"
But if I try to make a select from the database with SqlCommand, I get the following error:
Conversion failed when converting date and/or time from character string.
возникает на: Line 100: sda.Fill(dt);

I really don't like these dances with a tambourine because of DateTims. How to solve this problem in my case? And if someone has a good article about such problems, I will also be happy with a link)
---(Ответы в комментах)---

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2015-07-28
@Therapyx

To be honest, I'm tired of seeing such code. Your dances with tambourines are connected with the fact that you have no idea about the competent work with the database. The concatenation of the SQL query in the event handler in the code-behind is the decision of a person working with technology for about 20 minutes. There are a mountain of solutions. 1) Using ORM (using the Entity Framework with the DB First approach eliminates type casting and the possibility of injection) 2) Using stored procedures. 3) use of parameterized queries. The paradox is that if you use, for example, a stored procedure in a query, then you can use code like cmd.Parameters.AddIDateTime(sName, val) - and you don't need to type cast.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question