I'm trying to simply delete a full row from my SQL Server database table using a button event. So far none of my attempts have succeeded. This is what I'm trying to do:
public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + IDNumber, con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}
I keep receiving the error:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll An error occurred: Operand type clash: text is incompatible with int
All of the columns in the table are of TEXT
type. Why cannot I compare the function argument of type string
to the columns to find the match? (And then delete the row?)
As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around IDNumber.....
public static void deleteRow(string table, string columnName, string IDNumber)
{
try
{
using (SqlConnection con = new SqlConnection(Global.connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
{
command.ExecuteNonQuery();
}
con.Close();
}
}
catch (SystemException ex)
{
MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
}
}
}