Invalid column name sql error
Always try to use parametrized sql query to keep safe from malicious occurrence, so you could rearrange you code as below:
Also make sure that your table has column name matches to Name
, PhoneNo
,Address
.
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, PhoneNo, Address) VALUES (@Name, @PhoneNo, @Address)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@PhoneNo", txtPhone.Text);
cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
You probably need quotes around those string fields, but, you should be using parameterized queries!
cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;
Incidentally, your original query could have been fixed like this (note the single quotes):
"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";
but this would have made it vulnerable to SQL Injection attacks since a user could type in
'; drop table users; --
into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.