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
Related
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.
i am using formview to display data from access database, i want to be able to filter the formview using a FileNumber but the issue is that this file numbers are saved in such a way that they contain more records under one file number, so when searching the records should be displayed. but the file numbers are long and might differ in each record but the first characters are always the same, so i want to search using only the first characters. for example fileNo R:TM497.99; 19/14/ac; 219/99, i want to search it as r:tm497.99
below is my code
string fe = "";
if (startdate != "" && enddate != "" )
{
fe = "RenDate >= '" + startdate + "' and RenDate <= '" + enddate+ "'";
}
else if (startdate != "" && enddate == "" )
{
fe = "RenDate >= '" + startdate+"'";
}
else if (startdate == "" && enddate != "" )
{
fe = "RenDate <= '" + enddate + "'";
}
if (paramm != "")
{
fe = "Mark ='" + paramm + "' OR TMNumber ='"+paramm+ "' OR FileNo ='" + paramm + "' ";
}
if (txp!= "")
{
fe = "Proprietor ='" + txp + "'";
}
if (fil != "")
{
fe = "[FileNo] like '%{0}%'";
}
markdatas.FilterExpression = fe;
//rebind GridView1
markdatas.DataBind();
}
I have grid view in which all question has been display from access database . now I want to perform the search operation in given text boxes ,user may enter the data in 1 text box or else in all text boxes ,depends upon user needs .My question is how many times condition has been give so that whatever user give information in any text box ,filtration is performed accordingly.
for eg : user gave only standard and marks than filtration must be perform where standard = "given value" and marks = "given value" only
I have given various condition on each control but its become too huge coding. now wants to minimize this so any suggestion must recommended.
My Code:
private void txt_marks_TextChanged(object sender, EventArgs e)
{
string marks = Convert.ToString(txt_marks.Text);
string q_type = Convert.ToString(cmbQType.SelectedValue);
if (q_type.Contains("[") || q_type.Contains("]") || q_type.Contains("*") || q_type.Contains("%"))
{
q_type = replacestring(q_type);
}
if (btnlanguage.Text != "" && txt_sub.Text != "" && txt_std.Text != "" && cmbQType.SelectedIndex != -1 && txt_marks.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '" + txt_std.Text.ToString() + "'and Chapter Like '" + btnlanguage.Text.ToString() + "%' and QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1 && txt_sub.Text != "" && txt_std.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '"+ txt_std.Text.ToString()+ "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1 && txt_sub.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format(" QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Marks = '"+ marks +"'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else
{
load_grid_view();
}
Similarly above coding has been done to every given control.
Thank you .
What about using some Function that take n arguments to do some checks?
private void txt_marks_TextChanged(object sender, EventArgs e)
{
string marks = Convert.ToString(txt_marks.Text);
string q_type = Convert.ToString(cmbQType.SelectedValue);
char[] q_types = { '[', ']', '%'};
if (ContainsChars(q_types, q_type))
{
q_type = replacestring(q_type);
}
if (NoEmpty(btnlanguage.Text, txt_sub.Text, txt_std.Text, txt_marks.Text) && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '" + txt_std.Text.ToString() + "'and Chapter Like '" + btnlanguage.Text.ToString() + "%' and QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (NoEmpty(txt_marks.Text, txt_sub.Text, txt_std.Text) && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%' and Standard Like '"+ txt_std.Text.ToString()+ "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (NoEmpty(txt_marks.Text, txt_sub.Text) && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("QuestionType Like '" + q_type + "' and Marks = '" + marks + "' and Subject Like '" + txt_sub.Text.ToString() + "%'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "" && cmbQType.SelectedIndex != -1)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format(" QuestionType Like '" + q_type + "' and Marks = '" + marks + "'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else if (txt_marks.Text != "")
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format("Marks = '"+ marks +"'");
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else
{
load_grid_view();
}
}
public static bool NoEmpty(params string[] strings)
{
return strings.All( x => x != string.Empty );
}
public static bool ContainsChars(IEnumerable<char> chars, string toTest)
{
return chars.Any(x => toTest.Contains(x));
}
Please note that I've written it with notepad++ so I don't have typo checks, so excuse me if there's any typo
Perhaps you can store the field query in the Tag property of each control (e.g. txt_marks.Tag would be set to "Marks ='{0}'") then you can define an extensiom method to get the query from a TextBox and another for the drop down, something like:
internal static string GetQuery(this TextBox textBox)
{
if(string.IsNullOrEmpty(textBox.Text)) return string.Empty;
return string.Format(textBox.Tag.ToString(), textBox.Text)
}
internal static string GetQuery(this ComboBox cmbBox)
{
if(cmbBox.SelectedIndex == -1) return string.Empty;
return string.Format(cmbBox.Tag.ToString(), cmbBox.SelectedValue)
}
Then you can just loop through the controls, call GetQuery and do a string.Join("and ", controlQueries.Where(q => !string.IsNullOrEmpty(q))
Thank you #KMoussa and #Sid .
With your Combine Both suggestion I made a Dynamic query in function and call this function on every control and also like to share with this site .
My function :
public void searching_query()
{
string grid_query = "";
int cnt_coma = 0;
string q_type = "";
if (txt_marks.Text != "")
{
string marks = Convert.ToString(txt_marks.Text);
}
if (cmbQType.SelectedIndex != -1)
{
q_type = Convert.ToString(cmbQType.SelectedValue);
// Removing the wild character in question type .
if (q_type.Contains("[") || q_type.Contains("]") || q_type.Contains("*") || q_type.Contains("%"))
{
q_type = replacestring(q_type);
}
}
// counting the number of fields has been enter ->(for entering "and" in between in query)
{
if (txt_std.Text != "")
cnt_coma = 1;
if (txt_sub.Text != "")
cnt_coma = 2;
if (Txt_chp.Text != "")
cnt_coma = 3;
if (cmbQType.SelectedIndex != -1)
cnt_coma = 4;
if (txt_marks.Text != "")
cnt_coma = 5;
}
// making query for searching .
if (txt_std.Text != "")
{
if (cnt_coma > 1)
grid_query = grid_query + "Standard Like '" + txt_std.Text.ToString() + "' and ";
else if (cnt_coma <= 1)
grid_query = grid_query + "Standard Like '" + txt_std.Text.ToString() + "'";
}
if (txt_sub.Text != "")
{
if (cnt_coma > 2)
grid_query = grid_query + "Subject Like '" + txt_sub.Text.ToString() + "%' and ";
else if (cnt_coma <= 2 )
grid_query = grid_query + "Subject Like '" + txt_sub.Text.ToString() + "%' ";
}
if (Txt_chp.Text != "")
{
if (cnt_coma > 3)
grid_query = grid_query + "Chapter Like '" + Txt_chp.Text.ToString() + "%' and ";
else if (cnt_coma <= 3 )
grid_query = grid_query + "Chapter Like '" + Txt_chp.Text.ToString() + "%'";
}
if (cmbQType.SelectedIndex != -1)
{
if (cnt_coma > 4)
grid_query = grid_query + "QuestionType Like '" + q_type + "' and ";
else if (cnt_coma <= 4 )
grid_query = grid_query + "QuestionType Like '" + q_type + "'";
}
if (txt_marks.Text != "")
{
grid_query = grid_query + "Marks = '" + Convert.ToString(txt_marks.Text) + "'";
}
//---------- Grid view Filteration
if (cnt_coma > 0)
{
DataTable dt = main_ds.Tables[0];
dt.DefaultView.RowFilter = String.Format(grid_query);
DGV_View.DataSource = main_ds.Tables[0].DefaultView;
}
else
{
load_grid_view();
}
}
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"
Invalid attempt to call Read when reader is closed. getting this error asp.net with c#?
i have used this code
string catalogNo = string.Empty;
string deleteID = string.Empty;
Globals.Initialize("Text", "select CatelogNo,DeleteID from tbl_admin_quotation where QuotationID='" + quotation3 + "' order by id asc");
Globals.dr = Globals.cmd.ExecuteReader();
while (Globals.dr.Read() == true)
{
catalogNo = Globals.dr[0].ToString();
deleteID = Globals.dr[1].ToString();
decimal taqty = 0;
Globals.Initialize("Text", "select qty from tbl_admin_quotation where DeleteID='" + deleteID + "'");
Globals.dr3 = Globals.cmd.ExecuteReader();
if (Globals.dr3.Read() == true)
{
taqty = Convert.ToDecimal(Globals.dr3[0].ToString());
}
Globals.dr3.Dispose();
Globals.dr3.Close();
Globals.Initialize("Text", "select Pqty,Hqty from tbl_admin_stock where CatelogNo='" + catalogNo + "'");
Globals.dr = Globals.cmd.ExecuteReader();
if (Globals.dr.Read() == true)
{
if (Convert.ToDecimal(Globals.dr[0].ToString()) != 0)
{
Globals.Initialize("Text", "update tbl_admin_stock set Pqty=Pqty+'" + Convert.ToDecimal(taqty) + "' where CatelogNo='" + catalogNo + "'");
Globals.cmd.ExecuteNonQuery();
}
else if (Convert.ToDecimal(Globals.dr[1].ToString()) != 0)
{
Globals.Initialize("Text", "update tbl_admin_stock set Hqty=Hqty-'" + Convert.ToDecimal(taqty) + "' where CatelogNo='" + catalogNo + "'");
Globals.cmd.ExecuteNonQuery();
}
}
Globals.dr.Dispose();
Globals.dr.Close();
}
Globals.dr.Dispose();
Globals.dr.Close();
Globals.Initialize("Text", "delete from tbl_admin_quotation where QuotationId=#QuotationId");
Globals.cmd.Parameters.AddWithValue("#QuotationId", quotation3);
Globals.cmd.ExecuteNonQuery();
UpdatePanelMain.Update();
GridviewBind();
If you've code with obvious problems and problems you can't find, fix the obvious problems first and then the obscure problems will likely become obvious:
Get rid of the globals rubbish and put using in the appropriate places and then having the Dispose() called from that rather than explicitly will also fix this problem.