When i click the insert button, my program always tell me that i have a SQL syntax error near CPF, but the error starts in the middle of the textbox, just as i write 190.890.567-45 in the text box and the program tells me that the error is near '567-45', here is the code:
private void btninserir_Click(object sender, EventArgs e)
{
string sql;
int numero;
sql = "select * from doador where CPF = " + txtCPF.Text;
DataTable dt = bd.executarconsulta(sql);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Doador já cadastrado!!!!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
if (txtNome.Text != "" || txtCel.Text != "" || txtCPF.Text != "" || txtEndereco.Text != "" || txtTelRe.Text != "" || int.TryParse(txtIdade.Text, out numero))
{
bd.ConectarBD();
sql = "INSERT INTO DOADOR(CPF, NOME, IDADE, TELCASA, TELCELULAR, ENDERECO) VALUES('" + txtCPF.Text + "','" + txtNome.Text + "'," + txtIdade.Text + ",'" + txtTelRe.Text + "','" + txtCel.Text + "','" + txtEndereco.Text + "')";
bd.executarcomandos(sql);
MessageBox.Show("Doador Cadastro com sucesso!!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Valor Invalido!!!!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtCPF.BackColor = Color.Red;
txtNome.BackColor = Color.Red;
txtEndereco.BackColor = Color.Red;
txtIdade.BackColor = Color.Red;
txtTelRe.BackColor = Color.Red;
txtCel.BackColor = Color.Red;
txtCPF.Focus();
}
}
}
Error message
Just add 'between text param in SQL. Like this:
sql = "select * from doador where CPF = '" + txtCPF.Text + "'";
Related
private void button1_Click(object sender, EventArgs e)
{
try
{
if (transaction_idTextBox.Text == "" || lastnameTextBox.Text == "" || firstnameTextBox.Text == "" || middlenameTextBox.Text == "" || txtYear.Text == "" || txtDoI.Text == "" || txtPoI.Text == "" || txtAddress.Text == "" || CB_Sex.Text == "" || txtCS.Text == "" || txtDoB.Text == "" || txtPoB.Text == "" || txtAmount.Text == "")
{
MessageBox.Show("All Fields Are Compulsory");
}
else
{
SqlCommand cmdinsert = new SqlCommand("Insert into [Transaction] values( ' " + transaction_idTextBox.Text + " ','" + lastnameTextBox.Text + "','" + firstnameTextBox.Text + " ','" + middlenameTextBox.Text + "','" + txtYear.Text + "','" + txtDoI.Text + "','" + txtPoI.Text + "','" + txtAddress.Text + "','" + CB_Sex.Text + "','" + txtCS.Text + "','" + txtDoB.Text + "','" + txtPoI.Text + "','" + txtAmount.Text + "' )", con);
con.Open();
cmdinsert.CommandType = CommandType.Text;
cmdinsert.ExecuteNonQuery();
MessageBox.Show("Data Added");
transactionDataGridView.Update();
transactionDataGridView.Refresh();
transaction_idTextBox.Text = "";
lastnameTextBox.Text = "";
firstnameTextBox.Text = "";
middlenameTextBox.Text = "";
txtYear.Text = "";
txtDoI.Text = "";
txtPoI.Text = "";
txtAddress.Text = "";
CB_Sex.Text = "";
txtCS.Text = "";
txtDoB.Text = "";
txtPoB.Text = "";
txtAmount.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
For first : Add "LoadData();" at the end of Your code
Secondly add this to populate DataGridView:
public void LoadDataEQ()
{
DataTable AllDataTable = new DataTable();
string SqlCommand = "SELECT * FROM Transaction";
SqlDataAdapter SQLDA = new SqlDataAdapter(SqlCommand , con);
SQLDA.Fill(AllDataTable);
SQLDA.Dispose();
dataGridView1.DataSource = AllDataTable;
}
I am trying to save data into my database using the value stored in a session, however, the value must be of type int as stated in the database. how do I go about doing this? the code for the insertion is below.
protected void btnSave_outcome_Click(object sender, EventArgs e)
{
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand sqlCmd = new SqlCommand("OutcomeCreateOrUpdate", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#outcomeID", (hfoutcomeID.Value == "" ? 0 : Convert.ToInt32(hfoutcomeID.Value)));
sqlCmd.Parameters.AddWithValue("#learning_activity", (ddlActivity.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
sqlCmd.Parameters.AddWithValue("#audience", (txtAudience1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#condition", (txtCondition1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#bloom_level", (ddlCategory1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#verb", (ddlVerb1.SelectedValue.Trim()));
sqlCmd.Parameters.AddWithValue("#product", (txtProduct2.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#degree", (txtDegree1.Text.Trim()));
sqlCmd.Parameters.AddWithValue("#statement", ("Given " + txtCondition1.Text.Trim() + ", " + txtAudience1.Text.Trim() + " Will be able to " + ddlVerb1.SelectedItem.Text + " " + txtProduct2.Text.Trim()+ " " + txtDegree1.Text.Trim() +"."));
//sqlCmd.Parameters.AddWithValue("#moduleID", (ddlmodules.SelectedIndex));
sqlCmd.ExecuteNonQuery();
con.Close();
//string objectiveID = hfobjectiveID.Value;
string outcomeID = hfoutcomeID.Value;
Clear();
if (outcomeID == "")
lblSuccessMessage.Text = "Saved Successfully";
else
lblSuccessMessage.Text = "Updated Successfully";
//FillGridView(); for outcomes
new_outcome.Visible = true;
}
and I created the session as follows
protected void redirect_outcomes_Click(object sender, EventArgs e)
{
Session["objectiveID"] = objectiveID.ToString();
//Session["module"] = ddlmodules.SelectedValue;
//Response.Redirect("learningoutcomes.aspx?MultiView1.ActiveIndex=" +2);
final_objective1.Text = "Given " + txtCondition.Text.Trim() + ", " + txtAudience.Text.Trim() + " Will be able to " + txtVerb.Text.Trim() + " " + txtProduct.Text.Trim() + " .";
MultiView1.Visible = false;
GoToAudience1.Visible = false;
MultiView2.ActiveViewIndex = 0;
}
Your code:-
sqlCmd.Parameters.AddWithValue("#objectiveID", int.Parse(Session["objectiveID"].ToString()));
My suggestion:-
if(Session["objectiveID"] != null)
{
sqlCmd.Parameters.AddWithValue("#objectiveID", Convert.ToInt32(Session["objectiveID"]));
}
No need to use try parse/parse because you are storing only integer value in session. So session have either empty or integer value.
I'm really having trouble adding a condition that show message when user left the text box blank.I've tried every way that i know of to change it but it's not working at all.I have "5" textbox and hiding and showing them based on selected combobox item value for example if i selected firearm it should all five textbox and if i selected ammo then it should only show three textbox(1,2 and 3).And it should show message box warning me if i left a single textbox blank.
But the problem is during the ammo setting the message box kept showing up even though i have filled all of the textfield.Is there something wrong with my if else statement?
private void insertbtn_Click(object sender, EventArgs e)
{
string mysql = "";
if (comboBox1.SelectedItem.ToString() == "Firearm")
{
mysql = "insert into Firearm(Fid,Fname,Ftype,Manufacturer,Price) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "','" + textBox5.Text + "')";
}
if (comboBox1.SelectedItem.ToString() == "Ammo")
{
mysql = "insert into Ammo(Aid,Atype,Coating,Metal) values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "')";
}
if (comboBox1.SelectedItem.ToString() == "Ammo" && textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" )
{
MessageBox.Show("Please Fill all of the text fields");
}
else if (comboBox1.SelectedItem.ToString()=="Firearm" && textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "" || textBox4.Text == "" || textBox5.Text=="" )
{
MessageBox.Show("Please Fill all of the text fields");
}
else
{
try
{
SqlConnection conn = new SqlConnection(dbsource);
conn.Open();
SqlCommand cmd = new SqlCommand(mysql, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("New Data Inserted!");
conn.Close();
}
catch (SqlException)
{
MessageBox.Show("Error!!!");
}
}
}
Your problem is probably at this line:
if(comboBox1.SelectedItem.ToString() == "Ammo" &&
textBox1.Text == "" ||
textBox2.Text == "" ||
textBox3.Text == "")
I assume you want to say that is the value is "Ammo" and one of the text boxes are empty: (add another set of ()
if(comboBox1.SelectedItem.ToString() == "Ammo" &&
(textBox1.Text == "" ||
textBox2.Text == "" ||
textBox3.Text == ""))
And same for else if of "Firearm"
I am inserting some data into database using run-time SQL query, but before that i am checking is there any record exists or not. following is my code
protected void btnSignUp_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
try
{
using (SqlConnection con = new SqlConnection(cs))
{
string strgender = "";
if (Rb_Male.Checked)
strgender = "Male";
else if (Rb_Female.Checked)
strgender = "Female";
else
{
lblMsg.Text = "Please Select Gender";
lblMsg.ForeColor = Color.Red;
}
con.Open();
SqlCommand cmdcheck = new SqlCommand();
cmdcheck.CommandText = "select * from [Users] where E_Mail='" + #tb_Email.Text + "'";
cmdcheck.Connection = con;
//cmd.Parameters.AddWithValue("#em", tb_Email.Text);
SqlDataReader drd = cmdcheck.ExecuteReader();
if (drd.Read())
{
lblEmail.Visible = true;
lblEmail.Text = "Email Already Exsits";
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
else
{
string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')";
SqlCommand cmd = new SqlCommand(strcmd, con);
cmd.ExecuteNonQuery();
lblMsg.Text = "Account created sussecfully";
lblMsg.ForeColor = Color.Green;
clearallfields();
}
}
}
catch
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
}
else
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = " * Enter Required Field(s)";
}
}
The bellow part is working well in case if there no record associated with the particular email but if there is no record it goes to the else part and after executenonquery(); it goes to the catch part
if (drd.Read())
{
lblEmail.Visible = true;
lblEmail.Text = "Email Already Exsits";
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
else
{
string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')";
SqlCommand cmd = new SqlCommand(strcmd, con);
cmd.ExecuteNonQuery();
lblMsg.Text = "Account created sussecfully";
lblMsg.ForeColor = Color.Green;
clearallfields();
}
}
}
catch
{
lblMsg.ForeColor = Color.Red;
lblMsg.Text = "Account not created!!!";
}
kindly help me out with this..
Your insert statement doesn't specify which columns you want to add to the Users table.Place a breakpoint on the following line:
string strcmd = "insert into Users values ('" + #tbName.Text + "','" + #tbSName.Text + "','" + #tb_Email.Text + "','" + #tb_Pass.Text + "','" + #DropDownDay.Text + "','" + #DropDownMonth.Text + "','" + #DropDownYear.Text + "','"+ strgender +"')";
Take the value of strcmd and execute it in SQL Server Management Studio.You will see that it most likely fails.Fix the insert statement unti it works in SQL then copy it in your ASP.NET web application.
Also change your catch block and inspect the exception you're getting:
catch(Exception ex)
{
System.Diagnostics.Debugger.Break();
}
i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me
You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}