c# winForm adding value to number in texbox - c#

In my program i have several texboxes and buttons with coresponding names (ex. TextBox1 - buttonPlus1) like on the picture
but there are filled with numbers loaded from text file.
I want to write function that allows me to press button + and enlarge (add fixed number, for example 100) value from textbox. So far i have done:
private void buttonPlus1_Click(object sender, EventArgs e)
{
AddValue(sender,e);
}
private void AddValue(object sender, EventArgs e)
{
if (!(sender is Button))
return;
string controlName = (sender as Button).Name;
string textBoxName = controlName.Replace("buttonPlus", "textBox");
TextBox textBox = this.Controls.Find(textBoxName, false)[0] as TextBox;
int step = 100;
}
but i have no idea how to take value (as number) from textBox and add that step. Can somebody please help me? I tried to solve it by myself in many different ways, but it does not work

Get the value:
Convert.ToInt32(textBox.Text)
Save it to a variable, add 100 and just set it as usual.
P.S. You can also use Int32.Parse("")
textBox.Text = Convert.ToInt32(textBox.Text) + 100;
(You might need to .ToString() it)
EDIT:
As ltiong_sh mentioned, you should use TryParse rather then Parse:
int somevalue;
if(Int32.TryParse(textBox.Text, out somevalue))
{
textBox.Text = somevalue + 100;
}

You need to convert String to Integer
int txtValue = Convert.ToInt32(textBox.Text) + 100;

Make sure your validate the text in the text field. Else at the time of parsing it will throw an exception.
You can do this
int value = 0;
if(Int32.TryParse(textBox.Text, out value))
{
value += step;
textBox.Text = value.ToString();
}
else
{
//inform user to enter int
}

This is what you are looking for:
int newValue = Convert.ToInt32(textBox.Text) + step;
To put the value back in a textbox you can do the following:
textBox.Text = newValue.ToString();
Edit:
As mentioned by others you should use Int32.TryParse to prevent an error from being thrown.
if(Int32.TryParse(textBox.Text, out newValue))
{
newValue += step;
textBox.Text = newValue.ToString();
}

in button click get the textbox value and convert it to integer format and add 100 to it. after that reset textbox value to modified one's. Here is what you need.
private void buttonPlus1_Click(object sender, EventArgs e)
{
try
{
int txtValue = Convert.ToInt32(textBox.Text) + 100;
textBox.Text = txtValue.ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

Related

Adding textbox value, stay high value

Goal: The value I enter in the first box will be written in the second box
Goal: The second textbox will always write the highest value even if the first textbox changes
private void ModuleltextBox_TextChanged(object sender, EventArgs e)
{
try{
secondTxt.Text = firstTxt.Text;
var y = int.Parse(secondTxt.Text);
var x = int.Parse(firstTxt.Text);
if (y >= x)
{
//??
}
else if(x<y)
{
//??
}
}
catch (Exception){
}
You just need to set the Text property after comparing both text boxes value like :
try
{
var y = int.Parse(secondTxt.Text);
var x = int.Parse(firstTxt.Text);
if (y < x)
{
secondTxt.Text = x.ToString();
}
else
{
secondTxt.Text = y.ToString();
// or probably this line is not needed as y is already set in second TextBox
}
if first text box value is greater it will get set in secondTextBox otherwise the secondTextBox already have highest value.
I would think something like this would suffice?
private void ModuleltextBox_TextChanged(object sender, EventArgs e)
{
int x, y;
if (int.TryParse(firstTxt.Text, out x) && int.TryParse(secondTxt.Text, out y))
{
secondTxt.Text = Math.Max(x, y).ToString();
}
}
Put this piece of code in your textbox1 TextChanged event.
try
{
textBox2.Text = textBox1.Text;
int firstnum = int.Parse(textBox1.Text);
int secondnum = int.Parse(textBox2.Text);
}
catch
{
}
I think your second goal is not possible if you're using a TextChanged event since every changes you'll made in TextBox1 will be also made in TextBox2.

Windows Form App Float to String

Below is some of my code that isn't working. I wanted to see it could count the number of spaces in the text box so I'm having it display the number in a message box and it currently just throws a blank one. The problem is either in the float to string conversion or in the counter.
private static string _globalVar = "n";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
public Form1()
{
InitializeComponent();
button1.Text = "Enter";
}
string LNum { get; set; }
public void button1_Click_1(object sender, EventArgs e)
{
MessageBox.Show(LNum);
}
public void richTextBox1_TextChanged(object sender, System.Windows.Forms.KeyEventArgs e)
{
float n = 0;
if (Control.ModifierKeys == Keys.Space)
{
n = n + 1; ;
}
string.Format("{0:N1}", n);
string LNum = Convert.ToString(n);
}
What you are doing is an excellent way to learn how and when the events are raised and how they can be leveraged to customize an applications behavior and is something similar to what many of us have done over the years.
Based on what you say you are wanting to do, there are several issues. If you take a look at this code, it will do what you want.
public void button1_Click(object sender, EventArgs e)
{
int n = 0;
for (int counter = 0; counter < richTextBox1.TextLength; counter++)
{
if (richTextBox1.Text[counter] == ' ')
{
n++;
}
}
MessageBox.Show(n.ToString("N1"));
}
The key difference is that I am only looking at the entered text when the button is clicked. (TextChanged is run every time there is a change in the text displayed). I chose not to use a float variable to store the count of spaces as the count will always be an integer.
In addition, the parameter to TextChanged System.Windows.Forms.KeyEventArgs e is incorrect and will never compile if correctly bound to the TextChanged event.
The KeyEventArgs parameter is used by the KeyUp and KeyDown events. If you use these events, you will be looking to count every time the space bar is pressed and not the number of spaces in the text box. And like their name suggests, the events are raised every time a Key on the keyboard goes Up (Pressed) and Down (Released).

How to disable button if textbox is empty

First of all sorry for my bad english.
I'm beginner at C# and i made a Windows forms application but i can't disable one button if a textbox is empty.
I tried some of the Enabled methods but they didn't work. Hope someone can help me fix this. Thank you very much
public partial class ModulusForm : Form
{
public double nje;
public double dy;
public double pergjigja;
public double rezultati;
public ModulusForm()
{
InitializeComponent();
Button btn = new Button();
btn.Click += new EventHandler(butoniGjenero_Click);
}
private void butoniPerfundo_Click(object sender, EventArgs e)
{
this.Close();
}
private void butoniGjenero_Click(object sender, EventArgs e)
{
Random random = new Random();
nje = random.Next(1, 100);
dy = random.Next(1, 100);
if (nje > dy)
{ textboxPyetja.Text = "X = " + nje + " " + "dhe" + " " + "Y = " + dy; }
else if (nje > dy)
{
nje = random.Next(1, 100);
dy = random.Next(1, 100);
}
rezultati = nje / dy;
}
private void butoniPastro_Click(object sender, EventArgs e)
{
textboxPyetja.Clear();
textboxPergjigja.Clear();
textboxPergjigjaSakt.Clear();
}
private void butoniVerteto_Click(object sender, EventArgs e)
{
try
{
pergjigja = double.Parse(textboxPergjigja.Text);
}
catch
{
var informim = MessageBox.Show("Rishiko fushat!", "Verejtje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
if (textboxPergjigja.Text == "")
{
//nothin' baby
}
else
{
if (textboxPyetja.Text == "")
{
var informim = MessageBox.Show("Fusha e pyetjes eshte null!", "Verejtje", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (pergjigja == rezultati)
{
textboxPergjigjaSakt.Text = "Pergjigja eshte e sakte";
}
else
{
textboxPergjigjaSakt.Text = "Gabim." + " " + "Pergjigja e sakte eshte: " + "" + rezultati;
}
comboboxVargu.Items.Add(nje + " / " + dy + " = " + rezultati);
}
}
}
}
}
Credit to #Cody Gray for already suggesting this; I have just expanded it, so you can see how to implement and how it works
Overview
You can wire up an event handler for when your textboxPergjigja.Text's text has changed.
In the handler you create, you can then evaluate whether your button should be Enabled or not - using the string.IsNullOrWhiteSpace() check to set this.
First:
In your constructor for the form, subscribe to the textboxPergjigja.Text text box's TextChanged event.
Like this:
public ModulusForm()
{
InitializeComponent();
Button btn = new Button();
btn.Click += new EventHandler(butoniGjenero_Click);
// Add the subscription to the event:
textboxPergjigja.TextChanged += textboxPergjigja_TextChanged;
}
Next:
Add a handler that matches the correct delegate signature for that event.
Like this:
public textboxPergjigja_TextChanged(object sender, TextChangedEventArgs e)
{
// If the text box is not "empty", it will be enabled;
// If the text is "empty", it will be disabled.
butoniVerteto.Enabled = !string.IsNullOrWhiteSpace(textBoxPergjigja.Text);
}
This way, whenever the text in the textBoxPergjigja text box is changed; the evaluation is run and your button will always be enabled/disabled correctly.
Hope this helps! :)
Additional Info
You can also use textBox.Text.IsNullOrEmpty(), and it will still work - as suggested by #Cody
I have used string.IsNullOrWhiteSpace(), as opposed to textBox.Text.IsNullOrEmpty() for the following reasons:
The .IsNullOrEmpty() method only checks if the textBox.Text is either null or the total amount of characters is equal to 0.
The problem this might pose is, if the user only enters a space in the textbox, it is no longer Empty or null; thus this check will return true. If the logic of the program requires that an actual value be entered into the textbox, this logic can be flawed.
On the other hand: The string.IsNullOrWhiteSpace() check will check on 3 conditions - if the input string is null, Empty and contains only whitespace characters (space, newline etc.), also.
I hope this adds a little bit of extra fluff to give you an informed decision for future.
Hope it work!
private void YourTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(YourTextBox.Text))
YourButton.Enabled = false;
else
YourButton.Enabled = true;
}
Handle it on TextChanged event of your TextBox. (double click on your textbox control when in designed, which will automatically create the text changed event for you).
private void textboxPyetja_OnTextChanged(..blah blah)
{
if(String.IsNullOrWhitespace(txtTargetTextbox.Text)
{
//disable your control
}
else
{
//enable your control
}
}
Edit after 4 years - for some reason:
And here's a one-liner version, some people just love them...
private void textboxPyetja_OnTextChanged(..blah blah)
{
btnILoveButtons.Enabled = string.IsNullOrWhitespace(txtTargetTextbox.Text);
{
Try this:
if (String.IsNullOrEmpty(textboxPergjigja.Text))
butoniVerteto.Enabled = false;
else
butoniVerteto.Enabled = true;
add an event for edit text in the txtbox. when the text changes, enable the button
Change textBox1 for your textbox name then change button1 name for you button name
if (textBox1.Text == "")
{
button1.Enabled = false;
}
else
button1.Enabled = true;

Event located immediately after DataSource Update from ActiveEditor in Grid

What I need to do is calculated the value of one field in the grid, based on the values of other fields in the grid. I need to run this calculation After the value in one of the dependent cells is changed, but only if the value was a Valid entry. The EditValueChanged, Validating, and Validated events of the editor/repository all occur before the data is posted back into the datasource. I am wondering if there is any event I can hook into that will allow me to fire this calculation after the data has been post back into the datasource, but before control is returned to the user.
Sample Code
//calculation functions
private void SetCalcROP(MyObjectt Row)
{
//rop = m/hr
TimeSpan ts = Row.ToTime - Row.FromTime;
double diffDepth = Row.EndDepth - Row.StartDepth;
if (ts.TotalHours > 0)//donot divide by 0
Row.ROP = diffDepth / ts.TotalHours;
else
Row.ROP = 0;
}
private void SetCalcDeltaP(MyObject Row)
{
Row.DeltaPress = Row.SPPOnBtm - Row.SPPOffBtm;
}
//events
private void repNumberInput_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
if (vwDDJournal.FocusedColumn.Equals(colSPPOff) || vwDDJournal.FocusedColumn.Equals(colSPPOn))
SetCalcDeltaP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repNumberInput_NoNulls_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
if (vwDDJournal.FocusedColumn.Equals(colStartDepth) || vwDDJournal.FocusedColumn.Equals(colEndDepth))
SetCalcROP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repTimeEdit_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
SetCalcROP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repNumberInput_NoNulls_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextEdit TE = sender as TextEdit;
//null is not valid for this entry;
if (string.IsNullOrEmpty(TE.Text))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column may not be blank");
return;
}
else
{
double tmp;
if (!Double.TryParse(TE.Text, out tmp))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column must contain a number");
return;
}
}
}
private void repNumberInput_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextEdit TE = sender as TextEdit;
//null is not valid for this entry;
if (!string.IsNullOrEmpty(TE.Text))
{
double tmp;
if (!Double.TryParse(TE.Text, out tmp))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column must contain a number");
return;
}
}
}
private void repTimeEdit_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (vwDDJournal.FocusedColumn.Equals(colToTime))
{//dont bother to check from time
//TIME TRAVEL CHECK!!!!
DateTime FromTime = Convert.ToDateTime(vwDDJournal.GetRowCellValue(vwDDJournal.FocusedRowHandle, colFromTime));
TimeEdit te = sender as TimeEdit;
DateTime ToTime = Convert.ToDateTime(te.EditValue);
if (ToTime < FromTime)
{//TIME TRAVEL
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "To Time must be greater than From Time");
return;
}
}
}
the problem is that everywhere I call this from, and whether I use vwDDJournal.GetRowCellValue(...) or vwDDJournal.GetFocusedRow() as MyObject, I still get the old edit value.
Requirements
I have to have the input validated before running the calculation.
I have to run the calculation immediately after making the change.
... What I need to do is calculated the value of one field in the grid, based on the values of other fields in the grid.
The best way to accomplish this task is using Unbound Columns feature.
The following example demonstrates how to implement this feature by handling the ColumnView.CustomUnboundColumnData event:
// Provides data for the Total column.
void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e) {
if (e.Column.FieldName == "Total" && e.IsGetData) e.Value =
getTotalValue(e.ListSourceRowIndex);
}
// Returns the total amount for a specific row.
decimal getTotalValue(int listSourceRowIndex) {
DataRow row = nwindDataSet.Tables["Order Details"].Rows[listSourceRowIndex];
decimal unitPrice = Convert.ToDecimal(row["UnitPrice"]);
decimal quantity = Convert.ToDecimal(row["Quantity"]);
decimal discount = Convert.ToDecimal(row["Discount"]);
return unitPrice * quantity * (1 - discount);
}
Original example: How to: Add an Unbound Column Storing Arbitrary Data
You can also implement calculated value for unbound column using expressions:
GridColumn columnTotal = new GridColumn();
columnTotal.FieldName = "Total";
columnTotal.Caption = "Total";
columnTotal.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
columnTotal.UnboundExpression = "[Quantity] * [UnitPrice] * (1 - [Discount])";
gridView1.Columns.Add(columnTotal);
How about CustomCellValue?
After posting back to the data source refresh the data.
It's called whenever data is updated or view is changed.

converting textbox string to int

I'm trying to compare and multiply 2 random number variables with the int value entered in textboxes. If it is the correct increment the correct answers it does not increase the number although it increment works alone but it does not work with the textbox.
private void button1_Click(object sender, EventArgs e)
{
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == int.Parse(textBox4.Text))
{
correct++;
numbercorrect.Text = correct.ToString();
}
}
EDIT This is assuming that you are trying to have the user enter their guess before the button is pressed. Figured I would put this disclaimer here since there is confusion exactly what you are trying to do.
Looking at your current code sample, you are trying parse textBox4.Text, however, you are not setting textBox4.Text anywhere in your code sample. If textBox4.Text is string.Empty, int.Parse will throw an exception.
You should also look into doing Int.TryParse as it will tell you if it worked without throwing an exception.
EDIT: Since this is a guessing game, you should be validating the user's entry in textBox4 before continuing.
private void button1_Click(object sender, EventArgs e)
{
int answer;
if(!int.TryParse(textBox4.Text, out answer))
{
MessageBox.Show("Please Enter A Valid Integer.");
return;
}
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//int cv = +correct;
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
int s = x * z;
if (s == answer)
{
correct++;
numbercorrect.Text = correct.ToString();
}
}
You're comparing the textbox value to the product of two random values. Unless you know what those two random numbers are before you push the button, the if will fail.
This subroutine will be run as soon as Button1 is pressed. This will display two random numbers for the user to multiply. (Displayed in TB2 and TB3.)
Now, as soon as these numbers are displayed (and before the user has a chance to enter any answer) the program checks the value in TB4. This is empty, and throws an error when the parse is attempted.
Try breaking this into 2 subroutines with 2 buttons: one button to display a new problem, and one button to check the answer.
EDIT: Code added. (Note: I wrote this freehand--don't know if it would compile or not... just get the general idea. Note the button names.)
//This routine sets up the problem for the user.
private void btnGenerateProblem_Click(object sender, EventArgs e) {
//Get 2 random factors
int x = Randomnumber.Next(12);
int z = Randomnumber.Next(12);
//Display the two factors for the user
textBox2.Text = x.ToString();
textBox3.Text = z.ToString();
}
//This routine checks the user's answer, and updates the "correct count"
private void btnCheckAnswer_Click(object sender, EventArgs e) {
//Get the random numbers out of the text boxes to check the answer
int x = int.Parse(textBox2.Text);
int z = int.Parse(textBox3.Text);
//Compute the true product
int s = x * z;
//Does the true product match the user entered product?
if (s == int.Parse(textBox4.Text)) {
correct++;
numbercorrect.Text = correct.ToString();
}
}
Add verification code at the beginning of btnCheckAnswer_Click.
private void button1_Click(object sender, EventArgs e)
{
int result = Convert.ToInt32(textBox4.Text); int x, z;
if (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text) == result)
{
correct++;
numbercorrect.Text = correct.ToString();
Randomnumber.Next(12);
textBox2.Text = Randomnumber.Next(12).ToString();
textBox3.Text = Randomnumber.Next(12).ToString();
}
}

Categories