Search code examples
c#sqlt-sql

The data types text and varchar are incompatible in the equal to operator in C#


I am trying to access the data empname from the employeeTable, but the code I have written is giving me the following error:

The data types text and varchar are incompatible in the equal to operator.

Please suggest a solution

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string Connection = "Data Source=(local);Initial catalog=Test;Integrated Security=true";
    string Query = "SELECT * FROM  EmployeeTable WHERE empname='" + comboBox1.Text + "' ;";

    SqlConnection conn = new SqlConnection(Connection);
    SqlCommand cmd = new SqlCommand(Query, conn);

    conn.Open();
    SqlDataReader reader = cmd.ExecuteReader();

    while (reader.Read())     
    {
        textBoxEmpName.Text = reader["EmpName"].ToString();
    }
}

Solution

  • You can't compare text to varchar, but as an answer to anyone in the future with this problem simply convert the text column to varchar for the query.

    SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = '" + comboBox1.Text + "' ;";
    

    Always use parameters

    SELECT * FROM  EmployeeTable WHERE CONVERT(VARCHAR, empname) = @comboBox";