Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
getting error after converting

C#
private void LoadData()
    {
        con.Open();
      
        string s = "SELECT user_name FROM login" + " WHERE user_name='" + Label1.Text + "'";
        SqlCommand cmd = new SqlCommand(s, con);
        SqlDataReader Dr = cmd.ExecuteReader();
        if (Dr.Read())
        {
            con.Close();
            DateTime datetime = Convert.ToDateTime(Date.Text);
            string query = @"SELECT id,Build_name,Dept,Floor_no,Call_recv FROM  Tech_data where Call_assign='" + Label1.Text + "'  and date_time='" + datetime  + "'";

            SqlDataAdapter da = new SqlDataAdapter(query, con);
            DataTable table = new DataTable();
            da.Fill(table);

            GridView1.DataSource = table;
            GridView1.DataBind();
        }

    }
Posted
Updated 18-May-19 8:57am

There are a number of reasons for this, but the most common is that the date entered is not in the same format as the current Locale for the computer expects - or the user typed rubbish, of course! :laugh:

This first thing I would do is not use a text box for a Date entry: I would use a DateTimePicker instead if I could as this does not allow the user to enter an invalid date, and it also needs no conversion as it provides a DateTime value directly.

If this wasn't possible, I would use DateTime.TryParse or DateTime.TryParseExact instead of Convert.ToDateTime to eliminate user errors before I opened any connections or did anything else. Verify your data and report errors before you start on processing!
 
Share this answer
 
Use Parameters[^] collection for assigning user input parameters into SQL commands.
You can try this:
C#
string s = "SELECT user_name FROM login WHERE user_name = @u"; // there are no apostrophes around %u!
SqlCommand cmd = new SqlCommand(s, con);
cmd.Parameters.AddWithValue("@u", Label1.Text);

Do the same with date time - just create another command with @d parameter and put it into your SqlDataAdapter instead of plain sql query.

Why are you closing your connection (con) right after Dr.Read() ?
 
Share this answer
 
v3
C#
tried this worked fine . thnk you all


DateTime datetime = Convert.ToDateTime(Date.Text);
            SqlCommand cmnd = new SqlCommand("SELECT * FROM  Tech_data where Call_assign= @Call_assign and dateadd(dd, datediff(dd,0, [date_time]), 0) = @date_time ");
            cmnd.Connection = con;
            cmnd.Parameters.Add("@Call_assign", SqlDbType.VarChar).Value = Label1.Text;
            cmnd.Parameters.Add("@date_time", SqlDbType.DateTime).Value = datetime.Date;
            SqlDataAdapter da = new SqlDataAdapter(cmnd);
            DataSet ds = new DataSet();
            da.Fill(ds);
 
Share this answer
 
Hi Dear,

Please check that Date.Text is in which format.
If it is in dd/MM/yyyy or dd-MM-yyyy then it will give error while converting string to datetime in below statement.
DateTime datetime = Convert.ToDateTime(Date.Text);

in this case your date should be in MM-dd-yyyy or yyyy-MM-dd

In the other case please change below statement
string query = @"SELECT id,Build_name,Dept,Floor_no,Call_recv FROM Tech_data where Call_assign='" + Label1.Text + "' and date_time='" + datetime + "'";

to

string query = @"SELECT id,Build_name,Dept,Floor_no,Call_recv FROM Tech_data where Call_assign='" + Label1.Text + "' and date_time='" + datetime.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
 
Share this answer
 
Comments
Saja Nasser Alkazemi 6-Jun-17 6:16am    
OK thanx
If the problem persists while executing your code, perhaps it is due to two important reasons:

1. Yo have used the ' DateTime.Now.ToShortString' or similar auto conversion method, and
2. You changed the computers default Datetime format in the setting.

Change the Datetime format of the computer or change the autoconversion to 'parse' method.
 
Share this answer
 
v2
Comments
Richard Deeming 3-Oct-18 13:52pm    
Why would you think the problem persists when the question has already been marked as "solved"?

And if you'd used parameters, as the existing solutions suggest, then you wouldn't need to mess about with date formats.
hi have the same error when i try and execute my script

Here is my script that i am using:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InventoryStock
{
    public partial class Workstations : Form
    {
        public Workstations()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click_1(object sender, EventArgs e)
        {

        }

        private void Workstations_Load(object sender, EventArgs e)
        {
            comboBox3.SelectedIndex = 0;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            SqlConnection con = new SqlConnection(@"Data Source=sh-jasonk\dev;Initial Catalog=ITInventory;Integrated Security=True");
            //Insert Logic
            con.Open();
            bool Wkst_Status = false;
            if (comboBox1.SelectedIndex == 0)
            {
                Wkst_Status = true;
            }
            else
            {
                Wkst_Status = false;
            }
            
            SqlCommand cmd = new SqlCommand(@"INSERT INTO [dbo].[Workstations]
           ([Emp_Id]
           ,[Emp_Name]
           ,[Emp_Surname]
           ,[Department]
           ,[Company]
           ,[Hostname]
           ,[Wkst_Status]
           ,[Make]
           ,[Model]
           ,[SerialNumber]
           ,[ProductNumber]
           ,[Purch_Date]
           ,[WExpiry_Date]
           ,[Memory]
           ,[Processor]
           ,[HDD]
           ,[OS])
          
     VALUES
           ('" + Emp_ID.Text + "','" + txtName.Text + "','" + txtSurname.Text + "','" + comboBox1.Text + "','" + comboBox2.Text + "','" + txtHostName.Text + "','" + comboBox3.SelectedIndex + "','" + txtMake.Text + "','" + txtModel.Text + "','" + txtSN.Text + "','" + txtPN.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "','" + txtMem.Text + "','" + txtProc.Text + "','" + txtHDD.Text + "','" + txtOS.Text + "')",con);
          
            //Conversion failed here
            cmd.ExecuteNonQuery();
            con.Close();
            DateTime datetime = Convert.ToDateTime(dateTimePicker1.Text);
            //Reading Data
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [dbo].[Workstations]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.Rows.Clear();

            foreach (DataRow item in dt.Rows)
            {
                int n = dataGridView1.Rows.Add();
                dataGridView1.Rows[n].Cells[0].Value = item["Emp_Name"].ToString();
                dataGridView1.Rows[n].Cells[1].Value = item["Emp_Surname"].ToString();
                dataGridView1.Rows[n].Cells[2].Value = item["Department"].ToString();
                dataGridView1.Rows[n].Cells[3].Value = item["Company"].ToString();
                dataGridView1.Rows[n].Cells[4].Value = item["Hostname"].ToString();
                if ((bool)item["Wkst_Status"])
                {
                    dataGridView1.Rows[n].Cells[5].Value = "Active";
                }
                else
                {
                    dataGridView1.Rows[n].Cells[5].Value = "Inactive";
                }

              
                dataGridView1.Rows[n].Cells[6].Value = item["Make"].ToString();
                dataGridView1.Rows[n].Cells[7].Value = item["Model"].ToString();
                dataGridView1.Rows[n].Cells[8].Value = item["SerialNumber"].ToString();
                dataGridView1.Rows[n].Cells[9].Value = item["ProductNumber"].ToString();
                dataGridView1.Rows[n].Cells[10].Value = item["Purch_Date"].ToString();
                dataGridView1.Rows[n].Cells[11].Value = item["WExpiry_Date"].ToString();
                dataGridView1.Rows[n].Cells[12].Value = item["Memory"].ToString();
                dataGridView1.Rows[n].Cells[13].Value = item["Processor"].ToString();
                dataGridView1.Rows[n].Cells[14].Value = item["HDD"].ToString();
                dataGridView1.Rows[n].Cells[15].Value = item["OS"].ToString();
            }

        }
    
        private void label17_Click(object sender, EventArgs e)
        {

        }
    }
}
 
Share this answer
 
Comments
Richard Deeming 20-May-19 14:45pm    
If you want to ask a question, then ASK A QUESTION[^].

DO NOT post your question as a "solution" to somebody else's question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900