I am doing a selling invoice and i want the system to check if the quantity entered is a double value or no and if double value the quantity entered must be smaller than the quantity in the database.The validation of checking if the user enter a double or no is working fine but the other part of the code is not working fine.the code works after the user leaved the cell and enter it again and if he edit it the system is keep saving the old value(wrong value) but for the first part it is working fine if he enters letters the system give him an error and when he correct it the system take the new value and let him leave the sell normally the problem is in the second part here is my code:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5 || e.ColumnIndex == 6 || e.ColumnIndex == 7) // 1 should be your column index
{
if (Convert.ToString(e.FormattedValue) != "")
{
double i;
if (!double.TryParse(Convert.ToString(e.FormattedValue), out i))
{
e.Cancel = true;
MessageBox.Show("Insert correct numbers");
}
else
{
if (e.ColumnIndex == 5)
{
qty3 = Convert.ToDouble(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[5].Value);
string code = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
sqlClass c = new sqlClass();
con = c.getcon();
con.Open();
c.command("select quantity from items where code='" + code + "'");
cmd = c.getcmd();
double qty2 = Convert.ToDouble(cmd.ExecuteScalar().ToString());
if (qty3 > qty2)
{
e.Cancel = true;
MessageBox.Show("You don't have enough quantity \n Quantity available is:" + qty2);
}
else
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = null;
}
con.Close();
}
}
}
}
}
Related
I have the following DataGridview that requires to write only integer number, however if users writes any symbols/letter this error is promted. BTW this column is loaded from a database and value will be always an integer(so the entire columns is only for number only), so i dont know how to validate numbers when the users is editing the rows and not show this error.
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[5].Value != null)
{
if (dataGridView1.Rows[e.RowIndex].Cells[5].Value == System.DBNull.Value || dataGridView1.Rows[e.RowIndex].Cells[5].Value == null)//Check if cell is not nulll
{
dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.White;
}
else
{
int numero;
string mimonto = string.Empty + this.dataGridView1.Rows[e.RowIndex].Cells[5].Value;
bool res = true;
for (int i = 0; i < mimonto.Length; i++)
{
if (char.IsNumber(mimonto[i]) == true)// if position is a number
{
}
else
{
res = false;//value is not a number
}
}
if (res == true)
{
dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.White; //this is a number and color stays as white
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.Red;//color is red if it's not a number
dataGridView1.Rows[e.RowIndex].Cells[5].Value = 0;
MessageBox.Show("Debe ingresar valores nĂºmericos");
}
}
}
}
This is the error when a symbol/letter or anything thats not a number.
BTW is there any option to enable only number writting on cell? or is there any better option to solve this error?
enter image description here
Add values from two textboxes and display the sum in third textbox 3 but value of 1st aor 2nd textbox show in third textbox
TextBox3.Text = Convert.ToDouble(TextBox1.Text) + Convert.ToDouble(TextBox2.Text)
This will do it, just enter proper number. No exception handled.
To handle exception, use Double.TryParse instead of Convert.ToDouble.
Look at msdn example.
This will automatically change your value once you alter textbox1's value
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0)
{
textBox3.Text = Convert.ToString(Convert.ToDouble(textBox1.Text) + Convert.ToDouble(textBox2.Text));
}
if (textBox1.Text.Length > 0 && textBox2.Text.Length == 0)
{
textBox3.Text = textBox1.Text;
}
if (textBox1.Text.Length == 0 && textBox2.Text.Length > 0)
{
textBox3.Text = textBox2.Text;
}
if(textBox1.Text.Length == 0 && textBox2.Text.Length == 0)
{
textBox3.Text = "0";
}
}
edit: treat textbox value as 0 when its empty.
This example will still error if you enter non-numeric values into the textbox.
This question already has answers here:
How do I make a textbox that only accepts numbers?
(41 answers)
Closed 6 years ago.
here is my whole code fro the txtProductQuantity_TextChange:
protected void txtProductQuantity_TextChanged(object sender, EventArgs e)
{
TextBox txtQuantity = (sender as TextBox);
//int tempForTryParse = 0;
//if (!int.TryParse(txtQuantity.Text, out tempForTryParse))
//{
// txtQuantity.Text = txtQuantity.Text.Substring(0, txtQuantity.Text.Length - 1);
//}
DataListItem currentItem = (sender as TextBox).NamingContainer as DataListItem; // getting current item on where user wants to add or remove
HiddenField ProductID = currentItem.FindControl("hfProductID") as HiddenField;
Label lblAvailableStock = currentItem.FindControl("lblAvailableStock") as Label;
int tempInt = 0;
if (txtQuantity.Text == string.Empty || txtQuantity.Text == "0" || txtQuantity.Text == "1" || double.Parse(txtQuantity.Text) < 0 || !int.TryParse(txtQuantity.Text, out tempInt))
{
txtQuantity.Text = "1"; //default value is 1, no action
}
else
{
if (Session["MyCart"] != null) // not null means user has added a product in the shopping cart
{
if (Convert.ToInt32(txtQuantity.Text) <= Convert.ToInt32(lblAvailableStock.Text)) // check if quantity is greater than available stock
{
DataTable dt = (DataTable)Session["MyCart"]; // if quantity is less than the available stock, go inside the code
DataRow[] rows = dt.Select("ProductID = '" + ProductID.Value + "'"); // select specific row depending on the product id
int index = dt.Rows.IndexOf(rows[0]);
dt.Rows[index]["ProductQuantity"] = txtQuantity.Text; // putting the value in the txtQuantityTextbox. changing the product quantity in the data table
Session["MyCart"] = dt; // add updated value to datatable
}
else // error if quntity is greater than available stock
{
lblAvailableStockAlert.Text = " Alert: product buyout should not be more than the available stock!";
txtQuantity.Text = "1"; // automatically change the quantity back to 1.
}
}
}
UpdateTotalBill();
}
what i want to happen is to avoid letters being an input from the user. or something like it will be defaulted to "1" if they do.
Use an if statement to check
if(txtQuantity.Text.StartsWith("-")
{
//Code if negative
}
You could also parse the string as a number and then check if it is negative
if(int.Parse(txtQuantity.Text) < 0)
{
//Code if negative
}
So in the context of your code you could use it like this
if (txtQuantity.Text == string.Empty || txtQuantity.Text == "0" || txtQuantity.Text == "1" || txtQuantity.Text.StartsWith("-"))
{
txtQuantity.Text = "1"; //default value is 1, no action
}
or
if (txtQuantity.Text == string.Empty || txtQuantity.Text == "0" || txtQuantity.Text == "1" || int.Parse(txtQuantity.Text) < 0)
{
txtQuantity.Text = "1"; //default value is 1, no action
}
To avoid text being entered into the field, on the Text Changed event for the textBox you should add another criteria into this if statement, as well as an integer variable to act as an out
int tempInt = 0;
bool parsed = int.TryParse(txtQuantity.Text, out tempInt);
if (txtQuantity.Text == string.Empty || txtQuantity.Text == "0" || txtQuantity.Text == "1" || tempInt < 0 || !parsed)
{
txtQuantity.Text = "1"; //default value is 1, no action
}
managed to solve it.i added
int.Parse(txtQuantity.Text)<1)
to the first line of my code.
I am trying to use mod division to determine whether a year in a loop is a census or election year, and I have two issues:
1. I cannot get the wording in line with the year for ex:
It is like:
2000
this is an election year
this is a census year
2001
but I need it to say:
2000, this is an election year, this is a census year
2001 etc
2 : My math is some sort of wrong but I am having trouble identifying why or where, the division needs to apply to a user entered year range, and it needs to divide each year by 10, or 4, and the years that have no remainder are election or census years, but it is not doing that properly, it is not dividing all of the years, just some. My code is this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
startYr = int.Parse(textBoxStartYr.Text);
endYr = int.Parse(textBoxEndYr.Text);
if (int.TryParse(textBoxStartYr.Text, out startYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (int.TryParse(textBoxEndYr.Text, out endYr))
{
//correct
}
else
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true )
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items.Add("This is a census year");
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items.Add("This is an election year");
}
else { }
}
else
{
//nothing
}
}
}
Try this:
private void buttonGo_Click(object sender, EventArgs e)
{
// Variables
int startYr = 0;
int endYr = 0;
bool checkForCensus = checkBoxCensus.Checked;
bool checkForElection = checkBoxElection.Checked;
// Input Validation
string errorMsg = "";
if (!int.TryParse(textBoxStartYr.Text, out startYr))
errorMsg += "Please enter a four digit year";
if (!int.TryParse(textBoxEndYr.Text, out endYr))\
errorMsg += String.Format("{0}Please enter a four digit year",
errorMsg == "" ? "" : " ");
if (errorMsg != "")
{
MessageBox.Show(errorMsg);
return;
}
// Loop
for (int yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isCensusYear, isElectionYear;
if (checkForCensus && (yearDisp % 10) == 0)
isCensusYear = true;
if (checkForElection && (yearDisp % 4) == 0)
isElectionYear = true;
listBoxDisp.Items.Add(String.Format("{0}: {1}{2}{3}",
yearDisp.ToString(),
isCensusYear ? "this is a census year" : "",
(isCensusYear && isElectionYear) ? "," : "",
isElectionYear ? "this is an election year" : ""
));
}
}
Notes:
The empty if and else statements are unnecessary. I have removed the to make them more concise.
On the topic of conditionals in if statements: the ! means "not" or "the opposite of". Examples: !false == true and !true == false.
You do not need the initial int.Parse() statements because TryParse()'s second parameter is an out parameter (it outputs the parsed integer).
I created two variables which get the value of the check box. That way you don't have to check the value every time the loop is executed.
I used a ternary operator and String.Format() to determine what text to display.
Although you didn't mention it, I did change the input validation so that only one message box is displayed.
Try this for your listbox issue.
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
int index = listBoxDisp.Items.Add("Year:" + yearDisp.ToString());
if (checkBoxCensus.Checked == true)
{
if ((yearDisp % 10) == 0)
{
listBoxDisp.Items[index] += ",This is a census year";
}
else { }
}
else
{
//nothing needed
}
if (checkBoxElection.Checked == true)
{
if ((yearDisp % 4) == 0)
{
listBoxDisp.Items[index] += ",This is an election year";
}
else { }
}
else
{
//nothing
}
}
Try something like this:
private void buttonGo_Click(object sender, EventArgs e)
{
//Variables
int startYr = 0;
int endYr = 0;
int yearDisp = 0;
//Input Validation
if (!int.TryParse(textBoxStartYr.Text, out startYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
if (!int.TryParse(textBoxEndYr.Text, out endYr))
{
MessageBox.Show("Please enter a four digit year");
return;
}
//Loop
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = 0 == (yearDisp % 4);
bool isCensus = 0 == (yearDisp % 10);
if (isCensus && checkBoxCensus.Checked && isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a both a census year and an election year", yearDisp));
}
else if (isCensus && checkBoxCensus.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is a census year", yearDisp));
}
else if (isElection && checkBoxElection.Checked)
{
listBoxDisp.Items.Add(String.Format("{0} This is an election year", yearDisp));
}
else {
listBoxDisp.Items.Add(yearDisp.ToString());
}
}
}
Here's a more concise version of the for loop:
for (yearDisp = startYr; yearDisp <= endYr; yearDisp++)
{
bool isElection = (0 == (yearDisp % 4)) && checkBoxCensus.Checked;
bool isCensus = 0 == (yearDisp % 10) && checkBoxElection.Checked;
string text = yearDisp.ToString();
if (isCensus && isElection)
{
text += " This is a both a census year and an election year";
}
else if (isCensus)
{
text += " This is a census year", yearDisp;
}
else if (isElection)
{
text += " This is an election year";
}
listBoxDisp.Items.Add(text);
}
I am using the below code and when testing it, the textBoxes will allow number input, but you have to enter the complete number, then arrow back to enter the decimal. Otherwise the cursor jumps in front of the first number and will not allow the decimal to be entered. I would also like to allow the $ to be inputted first.
Any ideas how I can customize this textBox to do these functions allowing the calculations to function properly given below?
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
//Adding ToolTip
ToolTipService.SetToolTip(textBox1, "Enter Price, numbers first, then arrow back to add decimal.");
if (Double.TryParse(textBox1.Text, out value1))
{
textBox1.Text = value1.ToString();
}
textBox69.Text = value69.ToString();
if (textBox1.Text == null || textBox1.Text == "") value1 = 0;
{
textBox1.Text = value1.ToString();
if (textBox1.Text.EndsWith(".97") == true)
{
value20 = 0; value36 = 0; value69 = 0;
textBox20.Text = value20.ToString();
textBox36.Text = value36.ToString();
textBox69.Text = value69.ToString();
}
if (textBox1.Text.EndsWith("1") || textBox1.Text.EndsWith("2") || textBox1.Text.EndsWith("3") || textBox1.Text.EndsWith("4") || textBox1.Text.EndsWith("5") || textBox1.Text.EndsWith("6") || textBox1.Text.EndsWith("8") || textBox1.Text.EndsWith("9") || textBox1.Text.EndsWith("0") == true && (value1 < 100.00))
{
value69 = 1;
textBox69.Text = value69.ToString();
}
if (value1 > 100.01 && value1 < 149.99)
value69 = 2;
textBox69.Text = value69.ToString();
}
}