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
Related
I need to make a program that takes the input of a textbox (tb_1) and puts it in the second textbox (tb_2, multilined) when a button is pressed. It also needs to paste the code a specific amount of times, depending on the numericupdown digit. I have come this far, what do i do next? Thanks in advance.
(Note: it should probably be done within a class.)
{
public Form1()
{
InitializeComponent();
}
private void tb_1_TextChanged(object sender, EventArgs e)
{
}
private void btn_1_Click(object sender, EventArgs e)
{
string tekst = tb_1.Text;
tb_2.Text = tekst + Environment.NewLine;
tb_1.Clear();
tb_2.Text = tekst + Environment.NewLine;
}
}
}
This question already has answers here:
numeric-only textbox as a control in Visual Studio toolbox
(4 answers)
How do I make a textbox that only accepts numbers?
(41 answers)
Closed 5 years ago.
I am fairly new to C#, and this is my first attempt at creating a windows form. I created a very simple calculator which has two textboxes for users to enter numbers into. It has a(n) Add, Subtract, Multiply, and Divide button, and when the user enters values into the textboxes and clicks one of the buttons, the result is shown in a label. I would like to only allow integers to be input into the textboxes, but I don't know how I would be able to do this. Any advice or recommendations are appreciated. Thanks.
Here is my code so far:
namespace SimpleCalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void AddBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void SubtractBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) - Convert.ToInt32(textBox2.Text)).ToString();
}
private void MultiplyBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text)).ToString();
}
private void DivideBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) / Convert.ToInt32(textBox2.Text)).ToString();
}
}
}
You can use the below Function, and add it for Key press event of the text box.
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
Simplest way is to use the NumericUpDown control instead TextBox. NumericUpDown only allows numbers as their input and have similar properties of TextBox.
Access the value like this :
decimal answer=numericUpDown1.Value
`
Use NumericUpDown
You can find here a similar question How do I make a textbox that only accepts numbers?
make it simple try this
//function
public static void NumberOnly(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
//to call used this
NumberOnly("your textbox");
I've created a program to make bug templates and am having a problem with text not saving correctly.
I have a text file called TemplateTexts that holds all the text for each template, a template looks like this -
REQUIREMENTS
- Example
ADDITIONAL REQUIREMENTS
- Example
- Example
-----COPY BELOW THIS LINE-----
When the program closes it copies all of that into 1 line of a text file. (looks like this)
REQUIREMENTS- Example ADDITIONAL REQUIREMENTS- Example - Example-----COPY BELOW THIS LINE-----
The text file contains 20 lines of templates. The template is saved as 1 line of text into the text file, but when I go to open the program again, it turns that 1 line of text into multiple lines of text like how it is displayed in the first example.
Any idea why this might be happening? or is there a better way to save each template into a text file, possibly by separating it with flags or something?
Here's the code to my program:
public partial class Form1 : Form
{
static String buttonNamesPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonNames.txt";
String[] ButtonNames = System.IO.File.ReadAllLines(buttonNamesPath);
static String buttonTextPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonText.txt";
String[] ButtonText = System.IO.File.ReadAllLines(buttonTextPath);
private void SetupTextField()
{
comboBox1.Items.Clear();
comboBox2.Items.Clear();
for (int i = 0; i < ButtonNames.Length; i++)
{
comboBox1.Items.Insert(i, ButtonNames[i]);
comboBox2.Items.Insert(i, ButtonNames[i]);
}
}
public Form1()
{
InitializeComponent();
this.FormClosing += this.Form1_FormClosing;
}
private void Form1_Load(object sender, EventArgs e)
{
SetupTextField();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox1.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
ButtonNames[strIndex] = textBox1.Text;
ButtonText[strIndex] = richTextBox2.Text;
SetupTextField();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.IO.File.WriteAllLines(buttonNamesPath, ButtonNames);
System.IO.File.WriteAllLines(buttonTextPath, ButtonText);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox2.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
richTextBox1.Text = ButtonText[strIndex];
}
private void label3_Click(object sender, EventArgs e)
{
}
}
I also have 2 text files called ButtonNames.txt and ButtonText.txt
When you ask the RichTextBox for its Text property, it converts the rich text it contains internally to a plain-text string, and apparently by default it uses \n to translate line endings. Notepad doesn't recognize \n as a line ending (because it's looking for the official Windows line ending of \r\n), so it displays everything on one line. If you want to save with \r\n for line endings, use string.Replace on the result of RichTextBox.Text to replace \n with \r\n.
See this question and its answers for more details:
RichTextBox Newline Conversion?
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
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 9 years ago.
Improve this question
I want to restrict a textbox to accept only numbers in C#. How do I do that?
The most crude down and dirty way of doing it is doing something like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !char.IsDigit(e.KeyChar);
}
}
You're still not safe with this approach, as users can still copy and paste non-numeric characters into the textbox. You still need to validate your data regardless.
From others have said before me, we have to almost know what you will use this in, WinForms, ASP.NET, Silverlight ...
But now I take a chance that it is WinForm:)
private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
e.Handled = true;
}
has some bugs but easy way :D
private void textbox1_TextChanged(object sender, EventArgs e)
{
char[] originalText = textbox1.Text.ToCharArray();
foreach (char c in originalText)
{
if (!(Char.IsNumber(c)))
{
textbox1.Text = textbox1.Text.Remove(textbox1.Text.IndexOf(c));
lblError.Visible = true;
}
else
lblError.Visible = false;
}
textbox1.Select(textbox1.Text.Length, 0);
}
Have you tried the MaskedTextBox control in WinForms?
Have a look at something like this
Masked C# TextBox Control
This may not be the best way, but works ok for WPF TextBox...
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
string originalText = ((TextBox)sender).Text.Trim();
if (originalText.Length>0)
{
int inputOffset = e.Changes.ElementAt(0).Offset;
char inputChar = originalText.ElementAt(inputOffset);
if (!char.IsDigit(inputChar))
{
((TextBox)sender).Text = originalText.Remove(inputOffset, 1);
}
}
}
You can use the FilterTextBox of AJAX Control Toolkit. Using this you can allow/disallow any character type. This is quite flexible.
You can use the Microsoft.VisualBasic.Information.IsNumeric is numeric function. Just add the reference Microsoft.VisualBasic
private void textBox1_Validating(object sender,
System.ComponentModel.CancelEventArgs e) {
if (!Microsoft.VisualBasic.Information.IsNumeric(textBox1.Text)) {
e.Cancel = true;
} else {
// Do something here
}
}
This allows the user to enter scientific notation which is not trivial to filter for.
Not sure if this is the correct way, but it works for me, running it on the TextChanged event TextBox has:
private void CoordinateValidation(object sender, TextChangedEventArgs e) {
TextBox inputBox = e.OriginalSource as TextBox;
inputBox.TextChanged -= CoordinateValidation;
int caretPos = inputBox.CaretIndex;
foreach (TextChange change in e.Changes) {
if (inputBox.Text.Substring(change.Offset, change.AddedLength).Any(c => !ValidChars.Contains(c)) ||
inputBox.Text.Count(c => c == '.') > 1 ||
(inputBox.Text.Length > 0 && inputBox.Text.Substring(1).Contains('-'))) {
inputBox.Text = inputBox.Text.Remove(change.Offset, change.AddedLength);
caretPos -= change.AddedLength;
}
}
inputBox.CaretIndex = caretPos;
inputBox.TextChanged += CoordinateValidation;
}
Have a look at the below code
private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
This will be helpful but users can Copy and Paste characters :-)