problem with SQL and C#?

  • Thread starter Thread starter Mark
  • Start date Start date
M

Mark

Hi,

I have a little problem with trying to put information
from textBox into SQL database table.
Problem say that employeeId does not exsit but it is a
column in the table

code is

sqlDataAdapter2.InsertCommand.CommandText = "INSERT INTO
employee(" + employeeId
+ " ','"+eFName+"','"+eLName+"','"+ePosition+"','"+ePasswo
rd+") VALUES ('" + int.Parse(userIdTextBox.Text)
+ "', '" + firstNameTextBox.Text + "', '" +
lastNameTextBox.Text + "', '" + positionTextBox.Text
+ "', '" + passwordTextBox.Text + "')";


Can anybody help?

Mark
 
Try this:

sqlDataAdapter2.InsertCommand.CommandText = "INSERT INTO
employee(" + employeeId
+ ","+eFName+","+eLName+","+ePosition+","+ePasswo
rd+") VALUES (" + int.Parse(userIdTextBox.Text)
+ ", '" + firstNameTextBox.Text + "', '" +
lastNameTextBox.Text + "', '" + positionTextBox.Text
+ "', '" + passwordTextBox.Text + "')";

Regards,
Mikael
 
Oops...

This should work:

sqlDataAdapter2.InsertCommand.CommandText = "INSERT INTO
employee(
+employeeId+ ,+eFName+,+eLName+,+ePosition+,+ePassword+)
VALUES ("
+ int.Parse(userIdTextBox.Text) + ", '" +
firstNameTextBox.Text + "', '" + lastNameTextBox.Text
+ "', '" + positionTextBox.Text + "', '" +
passwordTextBox.Text + "')";

Regards
Mikael
 
In your particular case you are getting garbage in the CommandText. E.g.
employeeId looks like a variable and you are attempting to concatenate
"INSERT INTO employee(" with the *value* of employeeId variable, whatever it
is.
In your example you want to do this:

sqlDataAdapter2.InsertCommand.CommandText = "INSERT INTO employee(
employeeId, eFName, eLName, Position, ePassword ) VALUES (" +
userIdTextBox.Text + ", '" + firstNameTextBox.Text + "', '" +
lastNameTextBox.Text + "', '" + positionTextBox.Text
+ "', '" + passwordTextBox.Text + "')";

This however is a very bad practice. What you should have done to avoid all
these problems was to use command with parameters:
SqlCeCommand cmd = sqlDataAdapter2.InsertCommand;
cmd.CommandText = "INSERT INTO employee( employeeId, eFName, eLName,
Position, ePassword ) VALUES (?, ?, ?, ?, ?)";
cmd.Parameters.Add("@employeeId", SqlDbType.Int).Value =
Int32.Parse(userIdTextBox.Text);
cmd.Parameters.Add("@eFName", SqlDbType.NVarChar, 128).Value =
firstNameTextBox.Text; // Make sure the last parameter to Add() is a corect
coulmn width
Etc....

Finally, it is possible to have SqlCeDataAdapter to generate the insert
command automatically. To do this you need to define the primary key on your
table.
 
Back
Top