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"
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 wanted to insert data to microsoft access using c# and need to use class.
I've tried removing some textbox and look for some error and I feel that there might be some mistake in IF condition.
private void registerbutton_Click(object sender, EventArgs e)
{
-- CLASS --
RegStudent reg = new RegStudent();
reg.stdfname = fnametextbox.Text;
reg.stdlname = lnametextbox.Text;
reg.username = usernametextbox.Text;
reg.password = passwordtextbox.Text;
reg.dob = dobtextbox.Text;
reg.city = citytextbox.Text;
reg.state = statetextbox.Text;
reg.email = emailtextbox.Text;
reg.phoneno = ctcnotextbox.Text;
reg.phoneno2 = ctcnotextbox2.Text;
reg.course = coursetextbox.Text;
reg.emergencyname = emergencynametextbox.Text;
reg.emergencyphoneno = emergencynumbertextbox.Text;
reg.registerdate = registerdatetextbox.Text;
if (tptextbox.Text != "" && fnametextbox.Text != "" && lnametextbox.Text != "" && dobtextbox.Text != "" && usernametextbox.Text != "" && passwordtextbox.Text != "" && citytextbox.Text != "" && statetextbox.Text != "" && registerdatetextbox.Text != "" && emailtextbox.Text != "" && ctcnotextbox.Text != "" && ctcnotextbox2.Text != "" && coursetextbox.Text != "" && emergencynametextbox.Text != "" && emergencynumbertextbox.Text != "")
{
registerconnection.Open();
OleDbCommand insert = new OleDbCommand();
insert.Connection = registerconnection;
insert.CommandText = "Insert into StudentDatabase values (" + reg.stdfname + "','" + reg.stdlname + "','" + reg.username + "','" + reg.password + "','" + reg.dob + "','" + reg.city + "','" + reg.state + "','" + reg.email + "','" + reg.phoneno + "','" + reg.phoneno2 + "','" + reg.course + "','" + reg.emergencyname + "','" + reg.emergencyphoneno + ");";
insert.CommandType = CommandType.Text;
insert.Connection = registerconnection;
insert.ExecuteNonQuery();
MessageBox.Show("Data Have Been Registered.");
}
else
{
MessageBox.Show("error");
}
}
I expected that the output will be that the data will be saved.
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 + "'";
I have the following IF condition in one of my programs, I set the condition to validate whether the mandatory text fields are empty, if so, to display an Error message, But even when the mandatory fields are empty still the records being saved regardless of mandatory fields.
if (!txt_teacherid.Equals(null) && !txt_teacherid.Equals("") && !txt_teacherfname.Equals(null) && !txt_teacherfname.Equals("") && !txt_teacherlname.Equals(null) && !txt_teacherlname.Equals("") && !txt_teacherdob.Equals(null) && !txt_teacherdob.Equals("") && !txt_teachernationality.Equals(null) && !txt_teachernationality.Equals("") && !txt_teacheraddress.Equals(null) && !txt_teacheraddress.Equals(""))
{
String teacherid = txt_teacherid.Text.Trim();
String teacherfname = txt_teacherfname.Text.Trim();
String teacherlname = txt_teacherlname.Text.Trim();
String teachergender = opt_gender.SelectedItem.Value.ToString();
String teachercivilstatus = opt_civilstatus.SelectedItem.Value.ToString();
String teacherdob = txt_teacherdob.Text.Trim();
String teachernationality = txt_teachernationality.Text.Trim();
String teacheraddress = txt_teacheraddress.Text.Trim();
String teachercontactno = txt_teachercontactno.Text.Trim();
String teacherqualification = txt_teacherqualification.Text.Trim();
String teacherexperience = txt_teacherexperience.Text.Trim();
String teacherjobtitle = txt_teacherjobtitle.Text.Trim();
String teacherjoindate = txt_teacherjoindate.Text.Trim();
String imgpath = (String)Session["imagepath"];
DBConnection db = new DBConnection();
db.getConnection();
db.executeUpdateQuery("INSERT INTO Teacher (TeacherID,TeacherFirstName,TeacherLastName,TeacherGender,TeacherDOB,TeacherCivilStatus,TeacherNationality,TeacherQualification,TeacherExperience,TeacherJobTitle,TeacherAddress,TeacherContactNo,TeacherJoinDate,ImagePath) VALUES ('" + teacherid + "','" + teacherfname + "','" + teacherlname + "','" + teachergender + "','" + teacherdob + "','" + teachercivilstatus + "','" + teachernationality + "','" + teacherqualification + "','" + teacherexperience + "','" + teacherjobtitle + "','" + teacheraddress + "','" + teachercontactno + "','" + teacherjoindate + "','" + imgpath + "')");
Session["imagepath"] = null;
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "recordInserted();window.location.href='AdminRegisterTeacher.aspx'", true);
//Response.Redirect("AdminRegisterTeacher.aspx");
}
else
{
InnerError ie = new InnerError();
ie.throwError("Oops! There was an error, Make sure you have filled all mandatory data");
}
if (!txt_teacherid.Equals(null) && !txt_teacherid.Equals("")... is wrong as your are checking against the control txt_teacherid and not the text.
it should simply be
if (!String.IsNullOrEmpty(txt_teacherid.Text.Trim())... )
or use String.IsNullOrWhiteSpace (.Net 4 and up):
if (!String.IsNullOrWhiteSpace(txt_teacherid.Text) && ... )
And also note you should use parameterized queries to protect against SQL injection.
You should use one of the following:
string.IsNullOrEmpty()
string.IsNullOrWhiteSpace()
String has method which is .IsNullOrEmpty() which will return a boolean. Have you tried using that instead?
So would be:
if (!txt_teacherid.IsNullOrEmpty() && !txt_teacherfname.IsNullOrEmpty()&& !txt_teacherlname..IsNullOrEmpty() && !txt_teacherdob.IsNullOrEmpty() && !txt_teachernationality.IsNullOrEmpty() && !txt_teacheraddress.IsNullOrEmpty())
{
//do database stuff here
}
Use following code:
if (!String.IsNullOrEmpty(txt_teacherid) && !String.IsNullOrEmpty(txt_teacherfname) && !String.IsNullOrEmpty(txt_teacherlname) && !String.IsNullOrEmpty(txt_teacherdob) && !String.IsNullOrEmpty(txt_teachernationality) && !String.IsNullOrEmpty(txt_teacheraddress))
{
\\Save Data
}
else
{
\\show error
}
Use below code
if (!txt_teacherid.Text.Equals(null) && !txt_teacherid.Text.Equals("") && !txt_teacherfname.Text.Equals(null) && !txt_teacherfname.Text.Equals("") && !txt_teacherlname.Text.Equals(null) && !txt_teacherlname.Text.Equals("") && !txt_teacherdob.Text.Equals(null) && !txt_teacherdob.Text.Equals("") && !txt_teachernationality.Text.Equals(null) && !txt_teachernationality.Text.Equals("") && !txt_teacheraddress.Text.Equals(null) && !txt_teacheraddress.Text.Equals(""))
In place of your existing condition
I have a DataGridView which have 303 rows and 11 column. When I am going to save all this data to my sql table it takes 30-40 secs. Is this possible to save this data within 1-2 secs.
My Codes are like this
public SqlConnection conn;
SqlTransaction transaction;
string strconn = "data source=nabid;Persist Security Info=false;database=dbTest;user id=sa ;password=123;Connection Timeout = 10000";
conn = new SqlConnection(strconn);
conn.Open();
transaction = conn.BeginTransaction();
try
{
if (DataGridView1.Rows.Count > 0)
{
clsProd.DeleteRecord("[tbl1]", "");
foreach (DataGridViewRow r in DataGridView1.Rows)
{
if (r.Cells[0].Value != null)
{
Ticker = r.Cells[1].Value.ToString().Trim();
string values = "'" + tt.Trim() + "',";
values += "'" + r.Cells[1].Value.ToString().Trim() + "',"; // Ticker
values += (r.Cells[2].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[2].Value.ToString().Trim())) + ","; // LTP
values += Convert.ToDouble("0") + ","; // Open
values += (r.Cells[3].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[3].Value.ToString().Trim())) + ","; // High
values += (r.Cells[4].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[4].Value.ToString().Trim())) + ","; // LOW
values += (r.Cells[5].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[5].Value.ToString().Trim())) + ","; // Close
values += (r.Cells[6].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[6].Value.ToString().Trim())) + ","; // YCP
if (r.Cells[7].Value.ToString().Trim() == "--" || r.Cells[7].Value.ToString().Trim() == "")
chg_Prc = "0";
else
chg_Prc = r.Cells[7].Value.ToString().Trim();
values += Convert.ToDouble(chg_Prc.Trim()) + ","; // Change
values += (r.Cells[8].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[8].Value.ToString().Trim())) + ","; // Trade No
values += (r.Cells[9].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[9].Value.ToString().Trim())) + ","; // Volume
values += Convert.ToDouble("0") + ",";
if (r.Cells[2].Value.ToString().Trim() == "0.0" || r.Cells[2].Value.ToString().Trim() == "0.00" || r.Cells[2].Value.ToString().Trim() == "0")
tradeStatus = "N";
else
tradeStatus = "Y";
values += "'" + tradeStatus.Trim() + "',0";
addRecord("[tbl1]", values);
}
}
closeConnection();
this.Cursor = Cursors.Default;
}
catch (Exception exx)
{
this.Cursor = Cursors.Default;
errorTransaction();
return;
}
protected void ExecuteSQL(string sSQL)
{
SqlCommand cmd = new SqlCommand(sSQL, conn, transaction);
cmd.ExecuteNonQuery();
}
public void DeleteRecord(string tblName, string values)
{
string sSQL = "DELETE FROM " + tblName + " " + values;
ExecuteSQL(sSQL);
}
public void addRecord(string tblName, string values)
{
string sSQL = "INSERT INTO " + tblName + " VALUES(" + values + ")";
ExecuteSQL(sSQL);
}
public void closeConnection()
{
transaction.Commit();
conn.Close();
}
public void errorTransaction()
{
transaction.Rollback();
conn.Close();
}
Instead of calling function and giving overhead to program, make a single string of sql query for multiple inserts,updates and deletes.
Eg.
string sqlInsert="";
foreach (DataGridViewRow r in DataGridView1.Rows)
{
if (r.Cells[0].Value != null)
{
Ticker = r.Cells[1].Value.ToString().Trim();
string values = "'" + tt.Trim() + "',";
values += "'" + r.Cells[1].Value.ToString().Trim() + "',"; // Ticker
values += (r.Cells[2].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[2].Value.ToString().Trim())) + ","; // LTP
values += Convert.ToDouble("0") + ","; // Open
values += (r.Cells[3].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[3].Value.ToString().Trim())) + ","; // High
values += (r.Cells[4].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[4].Value.ToString().Trim())) + ","; // LOW
values += (r.Cells[5].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[5].Value.ToString().Trim())) + ","; // Close
values += (r.Cells[6].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[6].Value.ToString().Trim())) + ","; // YCP
if (r.Cells[7].Value.ToString().Trim() == "--" || r.Cells[7].Value.ToString().Trim() == "")
chg_Prc = "0";
else
chg_Prc = r.Cells[7].Value.ToString().Trim();
values += Convert.ToDouble(chg_Prc.Trim()) + ","; // Change
values += (r.Cells[8].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[8].Value.ToString().Trim())) + ","; // Trade No
values += (r.Cells[9].Value.ToString().Trim() == "" ? 0 : Convert.ToDouble(r.Cells[9].Value.ToString().Trim())) + ","; // Volume
values += Convert.ToDouble("0") + ",";
if (r.Cells[2].Value.ToString().Trim() == "0.0" || r.Cells[2].Value.ToString().Trim() == "0.00" || r.Cells[2].Value.ToString().Trim() == "0")
tradeStatus = "N";
else
tradeStatus = "Y";
values += "'" + tradeStatus.Trim() + "',0";
sqlInsert=sqlInsert+"Insert into " + tblName + " VALUES(" + values + ")";
}
}
ExecuteSQL(sqlInsert);
Try to have code like this.
This will decrease your overhead on system.
Hope its helpful.