I am creating a web form for my final project. I am working on a very basic fantasy league.
I have a page that lets the user select 11 players from drop down lists for each position and then insert them into a database. When I click submit on the bottom of the page, it should insert the text from each drop down list into the database.
Now when I try to insert the text of a drop down into the database, it shows me this error:
Invalid column name 'Courtois'.
Courtois is however text from the Goalkeeper drop down.
protected void btnConfirm_Click(object sender, EventArgs e)
{
string query = "INSERT into userPicks (Name) values ("+ ddlKeeper.Text + ")";
SqlConnection conn = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
int rowsInserted = cmd.ExecuteNonQuery();
if (rowsInserted > 0)
{
Response.Write("Data inserted successfully");
}
else
{
Response.Write("Data was not inserted into database");
}
}
The if statement is just to test if the data is being inserted or not.
I have tried hard coding the value that I need inserted, and that works just fine.
I think it is probably a wrong syntax or a wrong way that I am trying to insert the data into the database.
This is my code to bring up the names of players from a separate database:
protected void Page_Load(object sender, EventArgs e)
{
DataSet gk = new DataSet();
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmdgk = new SqlCommand("Select name FROM Players WHERE position='gk'", conn);
SqlDataAdapter adpgk = new SqlDataAdapter(cmdgk);
adpgk.Fill(gk);
ddlKeeper.DataSource=gk;
ddlKeeper.DataValueField = "Name";
ddlKeeper.DataBind();
}
Try this -
string query = "INSERT into userPicks (Name) values ('"+ ddlGK.Text + "')";
Better way do this will be to use parameterized query. Search for parameterized query and you should find plenty of examples.