Cannot be negative and avoid letter inputs on textbox [duplicate] - c#

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.

Related

Datagridview in C3

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();
}
}
}
}
}

Why string type is not converting to int type?

I want to add two numbers. I am getting values from button in my textbox. I also succeeded in splitting string into substrings and store values of these substrings in variables. But i am not able to convert string type to integer type. That results in concatenation not in addtion.
Note :
I am using MVC to perform this task. And in model value1 and value2 is string type in model
Here is my code snippet:
if (button == "1"){
if (model.textBox == "" || model.textBox == null || model.textBox.ToLower().Contains("please enter value")){
model.textBox = "1";
} else {
model.textBox += "1";
}
}
if (button == "2") {
if (model.textBox == "" && model.textBox == null) {
model.textBox = "2";
} else {
model.textBox += "2";
}
if (button == "+") {
if (model.textBox == "" && model.textBox == null){
model.errormsg = "Please enter a number ";
} else {
model.textBox += "+";
}
if (button == "=") {
if (model.textBox.Contains("+")) {
model.value1 = (model.textBox.Split('+'))[0];
int value1 = int.Parse(model.value1);
model.value2 = (model.textBox.Split('+'))[1];
int value2 = int.Parse(model.value2);
model.textBox = model.value1 + model.value2;
}
return View(model);
If i got you correctly all you need to do is:
model.textBox = (value1 + value2).ToString();
model.textBox is of type string, so, when you do model.textBox += "1"; the only possible operation is concatenation.
To add them as integers you first need to convert your textBox to int.
Something like the following will work:
model.textBox = (int.Parse(model.textBox) + 1).ToString();
Try using int.Parse(textBox.Text).
It will crash if there is a non-numeric character in the string, but that's nothing a try-catch block won't fix.
Hope this helps!
if (button == "=") {
if (model.textBox.Contains("+")) {
model.value1 = (model.textBox.Split('+'))[0];
int value1 = int.Parse(model.value1);
model.value2 = (model.textBox.Split('+'))[1];
int value2 = int.Parse(model.value2);
model.textBox = model.value1 + model.value2;
}
Replace above code snippet with below code snippet:
if (button == "=")
{
if (model.textBox.Contains("+"))
{
model.value1 = (model.textBox.Split('+'))[0];
model.value2 = (model.textBox.Split('+'))[1];
model.textBox1 = (int.Parse(model.value1) + int.Parse(model.value2)).ToString();
}

Argument index out of range in datagrid view c# windows form

Can anyone help me telling why argument index out range error occur in c# while selecting multiple rows in datagridview in c#...My code is also given bellow...the error is after the else if (comboBox2.Text == "Choice 2") portion......
if (comboBox2.Text == "")
{
comboBox2.Focus();
// comboBox2.BackColor = Color.Red;
}
else
{
if (comboBox2.Text == "Choice 1")
{
int ri = dataGridView1.CurrentCell.RowIndex;
int ci = dataGridView1.CurrentCell.ColumnIndex;
label4.Show();
textBox2.Show();
textBox2.Text = dataGridView1.SelectedRows[ri].Cells["course_name"].Value.ToString();
}
else if (comboBox2.Text == "Choice 2")
{
int ri = dataGridView2.CurrentCell.RowIndex;
int ci = dataGridView2.CurrentCell.ColumnIndex;
label3.Show();
textBox4.Text = dataGridView2.SelectedRows[ri].Cells["course_name"].Value.ToString();
textBox4.Show();
}
else if (comboBox2.Text == "Choice 3")
{
int ri = dataGridView3.CurrentCell.RowIndex;
int ci = dataGridView3.CurrentCell.ColumnIndex;
label2.Show();
textBox3.Text = dataGridView3.SelectedRows[ri].Cells["course_name"].Value.ToString();
textBox3.Show();
}
}
DataGridView.SelectedRows is a collection that contains the Rows selected. It has the same number of rows of the grid only if you select every row in the grid. But I think you are only selecting a few rows. So, the RowIndex of the current cell is not a valid index inside the SelectedRows collection.
You need to change your code to something more secure
if(dataGridView3.SelectedRows.Count > 0)
{
textBox3.Text = dataGridView3.SelectedRows[0].Cells["course_name"].Value.ToString();
....
or using the currentRow property.
DataGridViewRow currentRow = dataGridView3.CurrentRow;
if(dataGridView3.SelectedRows.Contains(currentRow))
{
textBox3.Text = currentRow.Cells["course_name"].Value.ToString();
....
but if you just want to set the TextBox3.Text to the cell "course_name" of the currentRow, then there is no need to involve the SelectedRows collection
if(dataGridView3.CurrentRow != null)
textBox3.Text = dataGridView3.CurrentRow.Cells["course_name"].Value.ToString();

C# behind Silverlight5 App TextBox enduser entry quirky

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();
}
}

Iterate through specific col in DGVs' & compare the string values

I got 2 datagrid views, First datagrid 1st col or Index 0 & the Second datagrid 1st col or Index 0.
How can i loop through a specific col in the datagridviews and look for the string values,if it matches with the list then go to a function.
My approach is not working. How can i do this?
private void b_calculate_Click(object sender, EventArgs e)
{
List<string> value = new List<String>() { "AE0", "AT1", "AT2", "AT3"};
value = new List<string>(datagridview1.Columns[0].Index);
List<string> value2 = new List<String>() { "BE0", "BT1", "BT2", "BT3"};
value2 = new List<string>(datagridview2.Columns[0].Index);
//First Combination
if((value.ToString() == "AT1" || value.ToString() == "AE0" ||
value.ToString() == "AT2")
&&
(value2.ToString() == "BT1" || value2.ToString() == "BE0"))
{
gottoFunction1();
}
//Second Combination
if((value.ToString() == "AT1" || value.ToString() == "AT2" )
&&
(value2.ToString() == "BT1" || value2.ToString() == "BT2"))
{
gottoFunction2();
}
}
Here's a routine that iterates through all available rows in both DataGridViews and does the processing shown in your method:
private void b_calculate_Click(object sender, EventArgs e)
{
for (var i = 0; i < dataGridView1.RowCount; i++)
{
if (dataGridView2.RowCount <= i)
break;
var cellFromDG1 = dataGridView1.Rows[i].Cells[0];
var cellFromDG2 = dataGridView1.Rows[i].Cells[0];
if (cellFromDG1.Value == null || cellFromDG2.Value == null)
{
// this could be the empty row that allows you to
// enter a new record
continue;
}
var value = cellFromDG1.Value.ToString();
var value2 = cellFromDG2.Value.ToString();
if ((value == "AT1" || value == "AE0" || value == "AT2") &&
(value2 == "BT1" || value2 == "BE0"))
{
gottoFunction1();
}
if ((value == "AT1" || value == "AT2") &&
(value2 == "BT1" || value2 == "BT2"))
{
gottoFunction2();
}
}
}

Categories

Resources