Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to change dynamically TextBox values.
i did this but its not working.
private void txtPrice_TextChanged(object sender, EventArgs e)
{
Convert.ToString(Convert.ToInt16(txtRate.Text) * Convert.ToInt16(txtQty.Text));
}
Try this instead
private void txtPrice_TextChanged(object sender, EventArgs e)
{
int rate = 0;
int qty = 0;
Int32.TryParse(txtRate.Text, out rate);
Int32.TryParse(txtQty.Text, out qty);
int total = rate * qty
// Set the new textBox value
// txtTotal should be your textbox value (what you have called it)
txtTotal.Text = total.toString()
}
I´m not a native C# developer so there might be some adjustments in the syntax.
As dotctor inferred, you're performing an operation but leaving it lost in space. You need to do something like this:
String valToChange;
private void txtPrice_TextChanged(object sender, EventArgs e)
{
valToChange = Convert.ToString(Convert.ToInt16(txtRate.Text) * Convert.ToInt16(txtQty.Text));
}
It's not clear which textbox value you want to change, though: you're using the changed event of txtPrice, so if you change that like this:
private void txtPrice_TextChanged(object sender, EventArgs e)
{
txtPrice.Text = Convert.ToString(Convert.ToInt16(txtRate.Text) * Convert.ToInt16(txtQty.Text));
}
...you will have a problem with the same event being called when you change that value. That's why I just put a "valToChange" there. You will have to adjust as needed.
You should assign a handler for TextChanged event of both txtQty and txtRate;
private void txtQty_TextChanged(object sender, EventArgs e)
{
UpdatePrice();
}
private void txtRate_TextChanged(object sender, EventArgs e)
{
UpdatePrice();
}
//code from user2893289 answer
private void UpdatePrice()
{
int r = 0, q = 0;
int.TryParse(txtRate.Text, out r);
int.TryParse(txtQty.Text, out q);
txtPrice.Text = (r*q).toString()
}
You should favor using int.TryParse over Convert.ToInt32 because Convert.ToInt32 will throw exception if input string format is not correct.
This works for me:
double rate = Convert.ToDouble(txtRate.Text);
int qty = Convert.ToInt32(txtQty.Text);
txtPrice.Text = ((double)rate*qty).ToString();
It assumes that txtRate contains a value such as "3.00" and that txtQty contains a value such as "7"
UPDATE
Since the rate is "readonly" this might be a better way to do it:
const double RANA_RASHIDS_RATE = 3.14; // or whatever it should be
. . .
txtRate.Text = RANA_RASHIDS_RATE.ToString(); // this is just for show
double rate = RANA_RASHIDS_RATE;
int qty = Convert.ToInt32(txtQty.Text);
txtPrice.Text = ((double)rate*qty).ToString();
UPDATE 2
Make sure there's a value in txtQty, or use a fake value (1):
const double RANA_RASHIDS_RATE = 3.14; // or whatever it should be
. . .
txtRate.Text = RANA_RASHIDS_RATE.ToString(); // this is just for show
double rate = RANA_RASHIDS_RATE;
int qty = 1;
if (!txtQty.Text.Trim().Equals(String.Empty))
{
qty = Convert.ToInt32(txtQty.Text);
}
txtPrice.Text = ((double)rate*qty).ToString();
There are other things you could do, if you want to get "fancy," such as monitor the change event of txtQty and only allow numerical values and backspace to be entered. That is left as an exercise for the questioner, though.
Related
This question already has answers here:
How to set a text box for inputing password in winforms?
(9 answers)
Closed 4 years ago.
This code is suppose to add a char "*" for every number added to the input variable. Every time you click the button it should add a * to a textbox. It works for the first one but then it doubles every time after that. Any advise what to change?
String input;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Security Code variables
securityCodeTextBox.Text = "";
securityCodeTextBox.PasswordChar = '*';
securityCodeTextBox.MaxLength = 5;
securityCodeTextBox.PasswordChar = '*';
accessLogBox.Text += input;
}
private void button1_Click(object sender, EventArgs e)
{
this.accessLogBox.Text = "";
input += 1;
this.securityCodeTextBox.Text += input;
this.accessLogBox.Text += input;
}
private void button2_Click(object sender, EventArgs e)
{
this.accessLogBox.Text = "";
input += 2;
this.securityCodeTextBox.Text += input;
this.accessLogBox.Text += input;
}
Each time you click a button, you append a number to input then append input to the Text. So Text is increasing at a "greater rate" than input.
So each button (let's say button1) click you get something like:
1->11 ->111 ->1111
1->111->111111->1111111111
etc.
Seems like you want ...Text=input rather than ...Text+=input
So the rest of the code is working fine but when it gets to the part where you have to select from predetermined values from the drop down menu, it doesn't display my options but instead allows the user to choose their own.
namespace A2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Items.Add("15%");
comboBox1.Items.Add("18%");
comboBox1.Items.Add("20%");
}
private void button1_Click(object sender, EventArgs e)
{
double amount, tax, tip, total, final;
amount = double.Parse(textBox1.Text);
tax = amount * 0.1;
labelTax.Text = tax.ToString();
total = amount + tax;
labelTotal.Text = total.ToString();
tip = amount * double.Parse(comboBox1.Text);
labelTip.Text = tip.ToString();
final = amount + tip + tax;
labelFinal.Text = final.ToString();
}
}
}
The SelectedIndexChanged event is fired when the user changes a selection in the combo box. With your code above, any time they choose a new item, you're adding 3 more.
However, as it stands now, the combo box is empty when the form loads, so this event will never fire (there are no choices to select). And then, as you mention, the user can type something in themselves.
To fix this, you might want to move that code into the Form_Load event instead. This way, the combo box will have the items added from the start. You also might want to set the DropDownStyle to DropDownList, which will prevent the user from being able to type in the combo box. And then you can set the SelectedIndex to 0 so the first item is selected:
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("15%");
comboBox1.Items.Add("18%");
comboBox1.Items.Add("20%");
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedIndex = 0;
}
Another problem you will run into is having the percent sign as part of the comboBox item text. double.Parse() will not know what to do with this. In order to resolve this, you can use the string.Replace() method to replace the percent character with an empty string before parsing as a double.
Additionally, you will want to divide this whole number by 100 so it's treated as a percentage:
tip = amount * (double.Parse(comboBox1.Text.Replace("%", "")) / 100);
Another approach to use data-binding and have strong typed values.
Use decimal as type for money related calculations
public class Tax
{
public decimal Value { get; }
public string Text { get => Value.ToString("0.## '%'"); }
public Tax(decimal value)
{
Value = value;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var taxes = new[]
{
new Tax(15),
new Tax(18),
new Tax(20),
}
comboBox1.ValueMember = "Value";
comboBox1.DisplayMember = "Text";
comboBox1.DataSource = taxes;
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
comboBox1.SelectedValue = 15;
}
Then in button click you can access selected value
var selectedTax = (decimal)combobox.SelectedValue;
or you can get whole selected object
var selectedTax = (Tax)combobox.SelectedItem;
My code is:
protected void txttotal_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtmaths.Text);
int b = Convert.ToInt32(txtsci.Text);
int c = Convert.ToInt32(txtenglish.Text);
int tot = a + b + c;
txttotal.Text = Convert.ToString(tot);
}
I am trying get the total marks to a textbox, but it is not working.Can you help me please?
You are trying to change the text in the same textbox that the text is changing, are you sure this is what you want to do?
Wouldn't you want to change the Total when the maths,sci and english values change? if so look at the following.
protected void txtmaths_TextChanged(object sender, EventArgs e)
{
UpdateTotals();
}
protected void txtsci_TextChanged(object sender, EventArgs e)
{
UpdateTotals();
}
protected void txtenglish_TextChanged(object sender, EventArgs e)
{
UpdateTotals();
}
protected void UpdateTotals()
{
int a = Convert.ToInt32(txtmaths.Text);
int b = Convert.ToInt32(txtsci.Text);
int c = Convert.ToInt32(txtenglish.Text);
int tot = a + b + c;
txttotal.Text = tot.ToString();
}
It looks like this method is the even handler for the TextChanged event of txttotal. I am guessing on "not working" here: You might run into a loop if you change a control in the handler to its changed-event.
You might want to check if you are hitting the handler because of a changed done by the handler.
Problem : there is no problem with the code but it looks you are writing your code inside total textbox TextChanged event handler, so who will raise the total textbox TextChanged event.
Solution : So you need to have some Button like Sumbit and you need to move the above code into Submit button click event handler as below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtmaths.Text);
int b = Convert.ToInt32(txtsci.Text);
int c = Convert.ToInt32(txtenglish.Text);
int tot = a + b + c;
txttotal.Text = Convert.ToString(tot);
}
You have the code to update txtTotal in txtTotal_TextChanged event. You need to put the code you have in some method and call it on change of txtmaths, txtsci, txtenglish instead of txttotal_TextChanged
protected void UpdateTotal()
{
txttotal.Text = Convert.ToInt32(txtmaths.Text) + Convert.ToInt32(txtsci.Text) + Convert.ToInt32(txtenglish.Text);
}
protected void txtmaths_TextChanged(object sender, EventArgs e)
{
UpdateTotal();
}
I can see this erroring due to type exceptions.
This is a safer way of doing this with less potential errors:
protected void txttotal_TextChanged(object sender, EventArgs e)
{
int a = 0;
int b = 0;
int c = 0;
if (!Int32.TryParse(txtmaths.Text, ref a))
// handle error...
if (!Int32.TryParse(txtsci.Text, ref b))
// handle error...
if (!Int32.TryParse(txtenglish.Text, ref c))
// handle error...
int tot = a + b + c;
txttotal.Text = Convert.ToString(tot);
}
I'm doing a "Who wants to be a millionaire"-like game and I'm stuck at how to check if the answer is the right answer or not.
I've made a struct that I can use to create some questions which looks like this:
struct Question
{
public string question, ansA, ansB, ansC, ansD;
public int correctAnswer;
}
Then I make questions like this:
Question ett = new Question();
ett.question = "Who is the richest?";
ett.ansA = "XXXX";
ett.ansB = "god";
ett.ansC = "vit";
ett.ansD = "röd";
ett.correctAnswer = 1;
And after that I put them in a list and retrieve a random question from there. The question in a label and the answers in four different buttons.
Random rnd = new Random();
int number = rnd.Next(0, NumberOfquestions+1);
var question = QuestionList[number];
lblquestion.Text = question.question;
button1.Text = question.ansA;
button2.Text = question.ansB;
button3.Text = question.ansC;
button4.Text = question.ansD;
The variable names aren't 100% correct because I've changed them for you to understand them since I have the variables in my language.
I'm stuck on how to check if the button clicked is right or not, and I have some thoughts about it but I'm unsure if that will work or if there are any better ways to do it.
One thing I thought was to make a method that check if its right, if the button return a value between 1-4 and check it against my int correctAnswer in the struct.
public int button1_Click(object sender, EventArgs e)
{
return 1;
}
Another thing I thought about was if I could make a method including all of the right answers in the game and search through if that match the text on my button?
Maybe not the best method to use.
namespace quiz
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
programmet();
}
public void btnNewGame_Click(object sender, EventArgs e)
{
}
public void BtnAvsluta_Click(object sender, EventArgs e)
{
this.Dispose();
this.Close();
}
public void programmet()
{
Question ett = new Question();
ett.fråga = "who is richest ?";
ett.svarA = "XXXX";
ett.svarB = "god";
ett.svarC = "vit";
ett.svarD = "röd";
ett.rättsvar = 1;
var QuestionList = new List<Question>();
QuestionList.Add(ett);
QuestionList.Add(tre);
QuestionList.Add(fyra);
QuestionList.Add(fem);
Random rnd = new Random();
int number = rnd.Next(0, numberOfQuestions -1);
var currentQuestion = QuestionList[number];
lblFråga.Text = currentQuestion.fråga;
button1.Text = currentQuestion.svarA;
button2.Text = currentQuestion.svarB;
button3.Text = currentQuestion.svarC;
button4.Text = currentQuestion.svarD;
}
public void button1_Click(object sender, EventArgs e)
{
/// here I want to use CurrentQuestion.question etc.
/// to do the "if(currentquestion.ansA == 1)"
}
}
}
Here is a possible solution:
Define a variable to store the current question (currentQuestion) that is accessible from the Click event handler of each button and from the method in which you select the question.
public void button1_Click(object sender, EventArgs e) {
if (currentQuestion.correctAnswer == 1)
CorrectAnswer();
else
WrongAnswer();
}
public void button2_Click(object sender, EventArgs e) {
// same for button2 ...
}
You could assign the Tags of your answer buttons, so button1.Tag = 1, button2.Tag = 2 etc. Then, for all your answer buttons, set their Click event to the same method, e.g.
void Answer_Click(object sender, EventArgs e)
In the method body, you can then access the Tag of the clicked button using...
int selectedAnswer = (int)((Button)sender).Tag;
To access your current question, make a private property or field in your Form1 class:
private Question CurrentQuestion;
and in your programmet() method, assign to it like this:
this.CurrentQuestion = QuestionList[number];
...so you can use
if (CurrentQuestion.correctAnswer == selectedAnswer) { ... }
Another way is when you're loading the answers onto the form set the appropriate button's tag to true and the rest false. Now in the common click event handler check the tag value of sender cast to a button and you have whether the answer is right
Why not just create two methods called CorrectAnswer() and IncorrectAnswer() and call the appropriate one from each button click. like so.
public void button1_Click(object sender, EventArgs e) {
//if answer is correct
CorrectAnswer();
public void button2_Click(object sender, EventArgs e) {
//if answer is incorrect
IncorrectAnswer();
hope this helps
On my GUI (Graphical User Interface), I have a button named Enter and a label.
When I click Enter, I want my result to be shown in the label. How do I do that?
For windows forms use the .Text property on the label:
private void btnEnter_Click(object sender, EventArgs e)
{
int themeaningoflifeuniverseandeverything = 420 / 10;
lblResult.Text = themeaningoflifeuniverseandeverything.ToString();
}
See exampe: ButtonEvent.zip
Double click on the button in the designer. This should create you a handler function for the buttons click event, something like this:
private void Button_Click(object sender, EventArgs e)
{
}
then in the function add the code to set the text of the lable:
lable.Text = myResult;
you should end up with something like this:
private void Button_Click(object sender, EventArgs e)
{
lable.Text = myResult;
}
As you said you have an int which is a percentage, and you have the value 0, I suspect that you are having problems getting the percentage not writing the value to the lable. so you might want to look at this question as I suspect that you have something like:
int valuea;
int valueb;
int result= valuea/valueb*100;
in this example if valuea=45 and valueb=100 the value of result will be 0, not 45.
int result = 0; // declare a private variable to hold the result
// Event handler for Click of Enter button
private void Enter_Click(object sender, EventArgs e)
{
result = Add(10,20); // set result to result of some function like Add
label.Text = result.ToString();
}
private int Add(int a, int b)
{
return a + b;
}
NOTE: I assume you are a beginner working with Winforms.
In winforms or webforms:
label.Text = Enter.Text;
Double click on button to generate event and write following code
private void Button_Click(object sender, EventArgs e)
{
lable1.Text = ur result; //result must be in string format otherwise convert it to string
}