Why is this code not displaying output on the textbox? - c#

I am beginning with C#. When I run the following code and click the generate button the output does not appear in the textbox. Why is this? I am calling the function palendrome and its not updating the textbox. What am I doing wrong? Am I missing something? What do I need to fix. I don't see the error. Please help. :(
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PalendromeChecker
{
public partial class Form1 : Form
{
int num;
int count;
static int result;
int setPalendromeValue;
int copyCount;
public Form1()
{
InitializeComponent();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
count = Int32.Parse(textBox2.Text);
copyCount = count;
if (!int.TryParse(textBox2.Text, out count))
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (count < 0 || count > 100)
{
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
public static int palendrome(int num)
{
int temp = num; ;
int r;
int rv = 0;
while (num > 0)
{
r = num % 10;
rv = rv * 10 + r;
num /= 10;
}
if (rv == temp)
{
result = temp;
return temp;
}
else
{
return 0;
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
while (copyCount != 0)
{
string resultInString = result.ToString();
textBox3.Text = resultInString;
textBox3.Visible = true;
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
num = Int32.Parse(textBox1.Text);
//MessageBox.Show(this.textBox1.Text);
if (!int.TryParse(textBox1.Text, out num))
{
//MessageBox.Show("This is a number only field");
//return;
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
else if (num < 0 || num > 1000000000)
{
// MessageBox.Show("Invalid Input needs to be between 0 and 1,000,000,000");
label4.Visible = true;
label4.Text = "Please enter a positive number within the range.";
}
}
private void label2_Click(object sender, EventArgs e)
{
}
private void label4_Click(object sender, EventArgs e)
{
label4.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
int palendromeValue;
while (count != 0)
{
palendromeValue = palendrome(num);
count--;
}
}
}
}

It is not generating any input on the textbox because your function palendrome is not generating in anyway output on any of textbox1 to textbox3.
Try this:
textBox1.Text = "output"; //Whatever output you want.

If you want to show result in textBox3 the code to update it's text property should be inside button click handler, not in text changed handler.
Also while (count != 0) or while (copyCount != 0) are like infinite loops (almost). They are going to make your form unresponsive. You need to avoid those.

Related

PictureBox in Windows Forms - How to open an image by clicking on it to see it in full resolution

How created a simple slideshow with a PictureBox element.
Now I would like to open an image by clicking on it to see it in full resolution - with the default app which is associated with .jpg files (e.g. Microsoft Photos). I think a click event on the PictureBox would be the way to go but I don't know what code to add. Couldn't find a good example on the internet.
Following the code I use so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Diashow
{
public partial class Form1 : Form
{
private string[] folderFile = null;
private int selected = 0;
private int begin = 0;
private int end = 0;
public Form1()
{
InitializeComponent();
this.pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
folderBrowserDialog1.SelectedPath = #"E:\MiscTest\";
timer1.Interval = 5000;
}
private void btnOpen_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string[] part1 = null, part2 = null, part3 = null;
part1 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpg");
part2 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.jpeg");
part3 = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.tif");
folderFile = new string[part1.Length + part2.Length + part3.Length];
Array.Copy(part1, 0, folderFile, 0, part1.Length);
Array.Copy(part2, 0, folderFile, part1.Length, part2.Length);
Array.Copy(part3, 0, folderFile, part1.Length + part2.Length, part3.Length);
selected = 0;
begin = 0;
end = folderFile.Length;
showImage(folderFile[selected]);
btnPrevious.Enabled = true;
btnNext.Enabled = true;
bntSlideshow.Enabled = true;
}
}
private void showImage(string path)
{
Image imgtemp = Image.FromFile(path);
pictureBox1.Image = imgtemp;
}
private void btnNext_Click(object sender, EventArgs e)
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (selected == 0)
{
selected = folderFile.Length - 1;
showImage(folderFile[selected]);
}
else
{
selected = selected - 1; showImage(folderFile[selected]);
}
}
private void nextImage()
{
if (selected == folderFile.Length - 1)
{
selected = 0;
showImage(folderFile[selected]);
}
else
{
selected = selected + 1; showImage(folderFile[selected]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
pictureBox1.Image.Dispose();
}
nextImage();
}
private void bntSlideshow_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
timer1.Enabled = false;
bntSlideshow.Text = "START Slideshow";
}
else
{
timer1.Enabled = true;
bntSlideshow.Text = "STOP Slideshow";
}
}
}
}

Creating a Counter for user input C#

Hey guys I need some help creating a counter for user input based on how much time they enter a guess to guess a random number from 1 - 100. So far this is what I have but it only output 1 count and does not count the next input. Can you please tell me what I am doing wrong?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
}
private void btnReset_Click(object sender, EventArgs e)
{
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
Random r = new Random();
int target = r.Next(0, 101);
int userGuess = int.Parse(txtGuess.Text);
int guessCount = 0;
if (userGuess == target)
{
guessCount++;
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = "You guess the right number " + "it took you: " + guessCount.ToString() + " guesses";
}
else if (userGuess < target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Yellow;
}
else if (userGuess > target)
{
guessCount++;
this.BackColor = System.Drawing.Color.Red;
}
lblCount.Text = "You made: " + guessCount.ToString() + " Guesses";
}
}
}
The issue with your code is that you are setting the guess counter to zero every time btnCheck is clicked. You need to make sure it is reset only once per guess session.
So this means that you need to move guessCount out as a class-level variable and make sure that you only reset it at the first run of the form and whenever btnReset is clicked.
Here's how I would refactor your code to achieve this:
public partial class frmGuess : Form
{
public frmGuess()
{
InitializeComponent();
}
private void frmGuess_Load(object sender, EventArgs e)
{
lblCount.Visible = true;
lblHowMuch.Visible = true;
ResetData();
}
private void btnReset_Click(object sender, EventArgs e)
{
ResetData();
}
private Random r = new Random();
private int guessCount;
private int target;
private void ResetData()
{
guessCount = 0;
target = r.Next(0, 101);
txtGuess.Text = "";
lblCount.Text = "";
lblHowMuch.Text = "";
this.BackColor = System.Drawing.Color.Empty;
txtGuess.Focus();
}
private void btnCheck_Click(object sender, EventArgs e)
{
int userGuess = int.Parse(txtGuess.Text);
guessCount++;
if (userGuess == target)
{
this.BackColor = System.Drawing.Color.DarkOliveGreen;
lblHowMuch.Text = String.Format(
"You guessed the right number it took you {0} guesses",
guessCount);
}
else
{
this.BackColor = userGuess < target
? System.Drawing.Color.Yellow
: System.Drawing.Color.Red;
}
lblCount.Text = String.Format(
"You made {0} Guesses",
guessCount);
}
}
You'll also notice that you were resetting the target each time btnCheck was clicked. That too needed to be moved to a class-level variable.
It's also a good habit to get in to making instances of Random a class-level variable too as there are circumstances where you can end up with less-than random numbers if you don't.
You'll notice that I moved all of the reset code into a new ResetData method that can get called both when the form loads and when btnReset is clicked.
It can't be so obvious. Why are you setting int guessCount = 0 in btnCheck_Click? Why don't you keep a global counter?
To make it global, take out int guessCount = 0; from the btnCheck_Click function and put it at the top where it appears like:
namespace GuessingGameGUI
{
public partial class frmGuess : Form
{
int guessCount = 0;
That way guessCount won't be continually reset to zero and then incremented each time you press the btnCheck button.

Simple Calculator Application in C#

I have two quick question about this simple calculator application I am trying to build in C#. (not homework by the way) I am trying to get the MessageBox.Show message to show in the multiply and add sections of my code, but they don't seem to be displaying even if I enter a negative value. The application just seems to do the math anyways. Also, this may be a dumb one, how do I get rid of the label5 text that appears in the application with out deleting it in the properties window?
Any help will be greatly appreciated, thanks!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddMultiply
{
public partial class AddMultiply : Form
{
public AddMultiply()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void txtFirstValue_TextChanged(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
while (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
while(double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue + secondValue;
lblAnswer.Text = answer.ToString();
}
private void btnMultiply_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
while (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
while (double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue * secondValue;
lblAnswer.Text = answer.ToString();
}
private void lblAnswer_Click(object sender, EventArgs e)
{
lblAnswer.Text = ""; //tries to get rid of "label5" text in application, but fails to do so
}
}
}
1)you should change the while to "if":
private void btnAdd_Click(object sender, EventArgs e)
{
double firstValue;
double secondValue;
double answer;
if (double.TryParse(txtFirstValue.Text, out firstValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
if(double.TryParse(txtSecondValue.Text, out secondValue) == false)
{
MessageBox.Show("The value(s) entered must be > 0");
}
answer = firstValue + secondValue;
lblAnswer.Text = answer.ToString();
}
2) where is Ladel5 ? It doesn't seem to be exist...
You can try the following code to show the MessageBox then the value is less than 0:
if (n1 < 0 || n2 < 0)
MessageBox.Show("Value less than ZERO ", "Value less than ZERO",MessageBoxButtons.OK , MessageBoxIcon.Exclamation);
As for getting rid of the label you can try :
label5.Visible = false;

Entering an "If" statement where it shouldn't [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
This code should monitor the user's keystrokes and stops him if s\he types a the wrong character .Yet when it comes to the if statement where it should compare to charecter everything just goes wrong
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.IO;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
void Rest()
{
counter = -1;
txt1.Enabled = true;
txt2.Enabled = true;
txt3.Enabled = true;
txt4.Enabled = false;
txt5.Enabled = true;
btn2.Enabled = false;
btn1.Enabled = true;
pass = "";
txt4.Clear();
Dic.Clear();
turns = 0;
}
string path;
int counter = -1;
string pass;
Dictionary<char, letterInfo> Dic;
int turns = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length) { MessageBox.Show("WrongInput(Shorter) !!! "); Rest(); }
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length) { MessageBox.Show("WrongInput !!!exceded length "); Rest(); }
if ((char)e.KeyValue != pass[counter]) { MessageBox.Show("WrongInput !!!Wrong charecter " + ((char)e.KeyValue).ToString() + " " + pass[counter].ToString()); Rest(); }
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
Dic[(char)e.KeyValue].end.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
private void button1_Click(object sender, EventArgs e)
{
string start = "";
string end = "";
string letter = "";
string all;
foreach (KeyValuePair<char, letterInfo> pair in Dic)
{
start = start + " " + pair.Value.start[0];
end = end + " " + pair.Value.end[0];
letter = letter + " " + pair.Key;
}
all = letter + "\n" + start + "\n" + end;
MessageBox.Show(all);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
txt1.Enabled = false;
txt2.Enabled = false;
txt3.Enabled = false;
txt4.Enabled = true;
txt5.Enabled = false;
btn2.Enabled = true;
btn1.Enabled = false;
pass = txt2.Text;
path = txt3.Text;
counter = Convert.ToInt32(txt1.Text);
Dic = new Dictionary<char, letterInfo>();
/* if (!File.Exists(path))
{
MessageBox.Show("Error..File not found");
Rest();
}Code to handle the xls files */
}
catch (Exception s)
{ MessageBox.Show(s.Message); }
}
}
}
This is the function where the problem occurs
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (counter < pass.Length)
{
MessageBox.Show("WrongInput(Shorter) !!! "); Rest();
}
else
{
turns++;
if (turns == Convert.ToInt32(txt1.Text))
{
MessageBox.Show("Test is Done ");
/*Writting files */
Rest();
}
}
}
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
if (Dic.ContainsKey((char)e.KeyValue))
{
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
else
{
Dic.Add((char)e.KeyValue, new letterInfo());
Dic[(char)e.KeyValue].start.Add(DateTime.UtcNow.ToString("HH:mm:ss.fff"));
}
}
And those are the problematic if statements
counter++;
if (counter >= pass.Length)
{
MessageBox.Show("WrongInput !!!exceded length "); Rest();
}
if ((char)e.KeyValue != pass[counter])
{
MessageBox.Show("WrongInput !!!Wrong charecter "+((char)e.KeyValue).ToString()+" "+pass[counter].ToString()); Rest();
}
You enter into if (counter >= pass.Length) because:
counter = -1; //starts at -1
pass = ""; //starts at empty string (length of zero)
Neither of these variables change in your code until:
counter++; //counter is now 0
counter is now equal to pass.Length. So the if statement is true and "WrongInput !!!exceded length " is printed.
You dont set the value of pass until button 2 is clicked. So on each keypress event that is fired, the pass value is empty.
In if ((char)e.KeyValue != pass[counter]) you are trying to compare the key entered, with the character number in pass. pass is empty and counter increments until you hit button 2. So e.Keyvalue will not equal pass[counter] every time.

Right to left typing in text box?

I have a Currency Textbox with a mask.
Mask is shown in textbox as --------.--
So user types in digits over the mask.
Now customer says he does not want to type in letter from left to right.
He wants to type from right to left.
Similar to what we have in calculator.
Now I tried changing the textbox's righttoleft property but that does not help my cause.
In the end I am stuck with handling the key event to manually change the position.
I am able to change the position but getting stuck completing the logic.
Here's how my code looks like :
void Textbx_KeyDown(object sender, KeyEventArgs e)
{
String temp = T.Text;
string temp2 = T.Text;
int CursorIndex = T.SelectionStart - 1;
for (int i = 0; i <= CursorIndex; i++)
{
if (i == 7)
{
temp2 = temp2.Insert(i, temp[i + 2].ToString());
temp2 = temp2.Remove(i, 2);
//i = i + 2;
}
else if (CursorIndex == i)
{
temp2 = temp2.Remove(i, 1);
temp2 = temp2.Insert(i, temp[i + 1].ToString());
}
else
{
// T.Text = T.Text.Insert(i + 1, "_");
temp2 = temp2.Insert(i, temp[i + 1].ToString());
temp2 = temp2.Remove(i + 1, 1);
}
}
T.Text = temp2;
// T.Text = T.Text.Insert(CursorIndex-1, temp[CursorIndex].ToString());
if (CursorIndex != -1)
T.SelectionStart = CursorIndex - 1;
}
Is there a better way to do this? If not how should I go about completing the logic?
There is a property for that in the textbox:
T.RightToLeft = RightToLeft.Yes
I have written this code for you; please try it:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
string mychar = "000000";
string mtxt;
int mypos = 6;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
maskedTextBox1.Text = mychar;
}
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
mtxt = mtxt + e.KeyChar;
mypos--;
mychar = mychar.Remove(mypos, mtxt.Length);
mychar = mychar.Insert(mypos, mtxt);
maskedTextBox1.Text = mychar;
}
}
}
try this using a maskedTextBox.
set TextMaskFormat Property = IncludePrompt
private void maskedTextBox1_Click(object sender, EventArgs e)
{
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
private void maskedTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != (char) Keys.Back)
{
String a = maskedTextBox1.Text + e.KeyChar;
maskedTextBox1.Text = a.Substring(1, a.Length - 1);
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
}
private void maskedTextBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
maskedTextBox1.Text = "_" + maskedTextBox1.Text;
maskedTextBox1.SelectionStart = maskedTextBox1.Mask.Length + 1;
}
}

Categories