Reputation: 27
When I try to fill textbox1
with a name, I get an exception indicating an invalid column name. When I fill it with a number it works.
The datatype of coach_name
is varchar(50)
.
The insert code is:
// connection setup code
SqlConnection conn = new SqlConnection(connString);
string Coach_Name = textBox1.Text;
try {
string Password1=textBox2.Text;
string Password2=textBox3.Text;
string Password=textBox2.Text;
if (Password1.Equals(Password2))
{
SqlCommand cmd = new SqlCommand("insert into CoachLogins values (" + Coach_Name + ",'" + Password + "')", conn);
conn.Open();
cmd.ExecuteNonQuery(); // hyi insert update delete ma btekhod shi
}
Upvotes: 0
Views: 223
Reputation: 10275
try to turn your code like this:
Point should be Cover
**using**
which Implements IDisposableusing (SqlConnection con=new SqlConnection(MyConnectionString)) { conn.Open(); using(SqlCommand command= new SqlCommand("insert into CoachLogins (Coach_Name,Password ) values (@Coach_Name , @Password )", conn)) { command.CommandType = CommandType.Text; command.Parameters.Add("@Coach_Name", SqlDbType.NVarChar,100).Value = TextBox1.Text; command.Parameters.Add("@Password", SqlDbType.NVarChar,100).Value = TextBox2.Text; ..... cmd.ExecuteNonQuery(); con.dispose } }
Upvotes: 0
Reputation: 22733
You haven't wrapped Coach_Name
in quotes, so it won't work if you pass it a string. Numeric values will work in a query like that as they don't have to be wrapped in quotes:
SqlCommand cmd = new SqlCommand _
("insert into CoachLogins values ('" + Coach_Name + "','" + Password + "')", conn);
Please read about using parameterised queries & SQL injection.
Also, I know this might be early days in your development work, but name your controls with something more useful than: button1
and textBox1
. It will soon become a mess if you carry on down that path.
Upvotes: 4