I'm trying to program the textboxes, so they do their instructions AFTER the textbox is left. Any ideas on how to do it? I tried smth with KeyUp, but don't really know how it works
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 For_homework
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var LoopResult = new List<int>();
var LoopParameters = new List<int>();
LoopParameters = TakeInput();
LoopResult = Looping(LoopParameters);
Result(LoopResult);
FinalResult(LoopResult);
}
private List<int> TakeInput()
{
var Loop = new List<int>();
Loop.Add(int.Parse(textBox1.Text));
Loop.Add(int.Parse(textBox2.Text));
Loop.Add(int.Parse(textBox3.Text));
Loop.Add(int.Parse(textBox4.Text));
Loop.Add(int.Parse(textBox5.Text));
Loop.Add(int.Parse(textBox6.Text));
return Loop;
}//Take the input
private List<int> Looping(List<int> LoopParam)
{
var LoopSum = new List<int>();
LoopSum.Add(0);
LoopSum.Add(0);
for (int i = LoopParam[0]; i <= LoopParam[1]; i += LoopParam[2])
{
LoopSum[0]+=i;
}
for(int i = LoopParam[3]; i <= LoopParam[4]; i += LoopParam[5])
{
LoopSum[1]+=i;
}
return LoopSum;
}//Do the loop and summarize
void Result (List<int> LoopResult)
{
resultA.Text = ""+LoopResult[0];
resultB.Text = ""+LoopResult[1];
}//Give result
void FinalResult(List<int> LoopResult)
{
if(LoopResult[0]>LoopResult[1])
{
WhoWins.Text = "Player A wins";
}
else if(LoopResult[1]>LoopResult[0])
{
WhoWins.Text = "Player B wins";
}
else
{
WhoWins.Text = "It's a draw";
}
}//Give final result
private void textBox1_TextChanged(object sender, EventArgs e)
{
int i = int.Parse(textBox1.Text);
if (i < 1 || i > 6)
label3.Text = "Wrong number";
}//Texbox evaluation
private void textBox2_TextChanged(object sender, EventArgs e)
{
int i = int.Parse(textBox2.Text);
if (i < 7 || i > 18)
label4.Text = "Wrong number";
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
int i = int.Parse(textBox4.Text);
if (i < 1 || i > 6)
label7.Text = "Wrong number";
}//Textbox evaluation
private void textBox5_TextChanged(object sender, EventArgs e)
{
int i = int.Parse(textBox5.Text);
if (i < 7 || i > 18)
label8.Text = "Wrong number";
}
}
}
The form itself
It told me my post is mostly code so I need to add more details
There is LostFocus TextBox Event that might be useful for you in this case:
private void textBox1_LostFocus(object sender, System.EventArgs e)
{
//Do something
}
And don't forget to register event in your designer file as
textBox1.LostFocus += new EventHandler(textBox1_LostFocus);
Related
I'm designing an interface using C# windows Forms and I want to send and receive 1024 bits using serial port, the number I'm sending is in the hex-form, so what I did was the next:
private void button2_Click(object sender, EventArgs e)
{
int i;
int a = 0;
byte[] mychar;
mychar = new byte[128];
string M = textBox1.Text;
for (i = 0; i < 127; i++ )
{
mychar[i] = Convert.ToByte((M.Substring(a,2)),16);
a += 2;
}
serialPort1.Write(mychar,0,127);
}
and to check if the data is correct or not, I shorted out both the transmitter and receiver so I can see what I send from textbox1 to be shown in textbox5, the problem is the textbox is shown the output as ASCII, and I couldn't tell how to convert it to Hex form ,(see my attempt as commented bellow):
private void displaytext(object s, EventArgs e)
{
textBox5.Clear();
textBox5.AppendText(RXstring);
//int value = Convert.ToInt32(RXstring, 16);
//string stringValue = Char.ConvertFromUtf32(value);
//textBox4.AppendText(stringValue);
}
so to summarize my problems:
1- Is the code to send data is correct?
2- How can I force the textbox to show the output as Hex?
thank you very much.
UPDATE this is my full code, maybe then you understand my problem :
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 Form3 : Form
{
public Form3()
{
InitializeComponent();
}
string RXstring = "";
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
RXstring = serialPort1.ReadExisting();
this.Invoke(new EventHandler(displaytext));
}
catch (System.TimeoutException)
{
}
}
private void displaytext(object s, EventArgs e)
{
textBox5.Clear();
textBox5.AppendText(RXstring);
//int value = Convert.ToInt32(RXstring, 16);
//string stringValue = Char.ConvertFromUtf32(value);
//textBox4.AppendText(stringValue);
}
private void pictureBox2_Click(object sender, EventArgs e)
{
serialPort1.Close();
Form1 myForm = new Form1();
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (!serialPort1.IsOpen)
{
serialPort1.Open();
button1.Enabled = false;
}
else
{
MessageBox.Show("Port is Open by other party!");
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
serialPort1.Close();
}
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
textBox2.Text = "0";
textBox3.Text = "0";
textBox4.Text = "0";
textBox5.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
int i;
int a=0;
byte[] mychar;
mychar = new byte[128];
string M = textBox1.Text;
for (i = 0; i < 127; i++ ) {
mychar[i] = Convert.ToByte((M.Substring(a,2)),16);
a += 2;
}
serialPort1.Write(mychar,0,127);
}
}
}
when I send data from textbox1 I want to be shown exactly as I send it in textbox5, can you help me in that ?
https://drive.google.com/file/d/0B5PXKMhwKWQRREtuMXBaZDA1LUU/view?usp=sharing
This MCVE shows how to convert between bytes and hexadecimal strings:
class Program {
static void Main(string[] args) {
byte[] bytes = FromHexString("0123456789ABCEF");
string text = ToHexString(bytes);
Console.Write(text);
Console.ReadKey(true);
}
static byte[] FromHexString(string hexString) {
byte[] result;
//determine length and handle case of uneven digit count
int length = hexString.Length / 2;
bool even = length * 2 == hexString.Length;
if(!even) {
length++;
}
//allocate memory
result = new byte[length];
int offset;
if(even) {
offset = 0;
} else {
//convert first digit, if digit count is uneven
result[0] = Convert.ToByte(hexString[0].ToString(), 16);
offset = 1;
}
for(int i = offset; i < result.Length; i++) {
//convert digit to byte
result[i] = Convert.ToByte((hexString.Substring(i * 2 - offset, 2)), 16);
}
return result;
}
static string ToHexString(byte[] bytes, bool upperCase = true) {
string format = upperCase ? "X" : "x";
//initialize result with double capacity as a byte in hex notation occupies 2 chars
StringBuilder result = new StringBuilder(bytes.Length * 2);
foreach(var #byte in bytes) {
result.Append(#byte.ToString(format));
}
return result.ToString();
}
}
I just added the following to the code :
string hex = "";
foreach (char c in RXstring)
{
int tmp = c;
hex += String.Format("{0:X2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
}
textBox5.AppendText(hex);
thank you any way :)
My app is to test for prime number. First time I enter a prime number, the result is true and number is displayed to user. But second time, the prime number check is not functioning as expected. Here is my code:
private void button1_Click(object sender, EventArgs e)
{
label3.Text = textBox1.Text;
float a = (float)Convert.ToDouble(textBox1.Text);
if (check_Number(ref a) == true)
{
ResultCheck.Text = "Input Number is Prime";
}
else if (check_Number(ref a) == false)
{
ResultCheck.Text = "Input Number is not Prime";
}
}
here is an example program that uses trial division.
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 PrimeCheck
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
double testthis = 0;
if (double.TryParse(textBox1.Text, out testthis))
{
if (CheckForPrime(testthis))
{
MessageBox.Show("prime time!!");
}
}
}
bool CheckForPrime(double number)
{//there are better ways but this is cheap and easy for an example
bool result = true;//assume we are prime until we can prove otherwise
for (double d = 2; d < number; d++)
{
if (number % d == 0)
{
result = false;
break;
}
}
return result;
}
}
}
I would like to do a program that after entering the number into the textbox and will display the appropriate images. For example, if you type 1 and 2, will show candle and a swan, the program will help in remembering the mnemonic system of numbers. This is my code:
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 WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string dane = textBox1.Text;
if (dane == "")
{
MessageBox.Show("No number");
}
else
{
bool jest_liczba = true;
try
{
double dane_ok = System.Convert.ToDouble(dane);
}
catch
{
MessageBox.Show("no int");
jest_liczba = false;
}
if (jest_liczba == true)
{
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string temp = textBox1.Text; //table
for (int i = 0; i < temp.Length; i++)
{
textBox1.Text = char.ToString(temp[i]);
}
string _katalog = #"c:\obrazki\"; //load picture
string _typ = ".jpg";
int _liczba;
if (Int32.TryParse(textBox1.Text, out _liczba))
{
pictureBox1.Image = Image.FromFile(_katalog + _liczba + _typ);
}
}
}
}
Program after entering a couple of numbers, displays only one image. Please help
I'm not sure what your for..loop is accomplishing. Just comment it out:
// string temp = textBox1.Text; //table
// for (int i = 0; i < temp.Length; i++)
// {
// textBox1.Text = char.ToString(temp[i]);
// }
That loop currently replaces the TextBox text with the last character of the temp string.
I'm new with c# and I need some help with my little app.
I want to have a button which starts the game over again after you are done, but the program needs to keep the total score. (you receive points for guessing)
Thanks in advance,
Philip
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 GuessingGame
{
public partial class TheUltimateGuessingGame : Form
{
public TheUltimateGuessingGame()
{
InitializeComponent();
}
int number;
int numberoftries;
int points;
int total = 0;
private void Form1_Load(object sender, EventArgs e)
{
Random generator = new Random();
number = generator.Next(0, 101);
MessageBox.Show("Try to guess a number between 1 and 100");
}
private void PlayAgainButton_Click(object sender, EventArgs e)
{
InitializeComponent();
}
private void button_guess_Click(object sender, EventArgs e)
{
int guess = Convert.ToInt32(textBox_guess.Text);
if (guess > number)
{
textbox_showdifference.Text = ("Guess was too high, try again!");
}
if (guess < number)
{
textbox_showdifference.Text = ("Guess was too low, try again!");
}
if (guess == number)
{
textbox_showdifference.Text = ("Awesome, guess was right!");
MessageBox.Show("It took you " + Convert.ToString(numberoftries) + " tries
to guess the right number");
if (numberoftries <= 3)
{
points = 10;
}
if (numberoftries >= 4 && numberoftries <= 6)
{
points = 5;
}
if (numberoftries >= 7)
{
points = 2;
}
total = total + points;
ScoreBoard1.Text = ("Here are your points --> " + points + "\nHere are your total points --> " + total);
}
++numberoftries;
}
private void exitbutton_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
Why not this?
private void PlayAgainButton_Click(object sender, EventArgs e)
{
Random generator = new Random();
number = generator.Next(0, 101);
numberoftries = 0;
MessageBox.Show("Try to guess a number between 1 and 100");
}
InitializeComponent is the method that parses your XAML to build the form. It's not intended to reset the state of your object.
This following code gives me the error below . I think I need "InvokeRequired" . But I don't understand how can I use?
Cross-thread operation not valid: Control 'listBox1' accessed from a thread other than the thread it was created on.
The code:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected static DataSet dataset = null;
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
SimulationFrameWork.MCSDirector run = new SimulationFrameWork.MCSDirector();
DataSet ds = run.Get();
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i]["result"].ToString() == "0")
{
dataset = run.Get(int.Parse(ds.Tables[0].Rows[i]["ID"].ToString()));
WorkerObject worker =
new WorkerObject(
int.Parse(dataset.Tables[0].Rows[i]["ID"].ToString()),
int.Parse(dataset.Tables[0].Rows[i]["Iteration"].ToString()),
listBox1, timer1);
Thread thread1 = new Thread(new ThreadStart(worker.start));
thread1.Start();
}
}
}
}
}
public class WorkerObject
{
private int id;
private int nmax;
private ListBox list1;
private System.Windows.Forms.Timer timer1;
public WorkerObject(int _id, int _nmax, ListBox _list1,
System.Windows.Forms.Timer _timer1)
{
id = _id;
nmax = _nmax;
list1 = _list1;
timer1 = _timer1;
}
public void start()
{
timer1.Stop();
int i, idaire, j;
double pi = 0.0, x, y;
Random rnd = new Random();
for (i = 0; i < 100; i++)
{
idaire = 0;
for (j = 0; j < nmax; j++)
{
x = rnd.Next(1, 10000) / (double)10000;
y = rnd.Next(1, 10000) / (double)10000;
if (Math.Pow(x, 2) + Math.Pow(y, 2) <= 1.0)
idaire += 1;
}
pi = 4 * (double)idaire / (double)nmax;
nmax *= 10;
list1.Items.Add(
"Iterasyon:" +
nmax.ToString() +
" ----->" +
pi.ToString() +
"\n");
System.Threading.Thread.Sleep(100);
}
SimulationFrameWork.MCSDirector run = new SimulationFrameWork.MCSDirector();
run.Update(id, pi);
list1.Items.Add("\n\n islem bitti...");
}
}
}
This should get you around it
private delegate void stringDelegate(string s);
private void AddItem(string s)
{
if (list1.InvokeRequired)
{
stringDelegate sd = new stringDelegate(AddItem);
this.Invoke(sd, new object[] { s });
}
else
{
list1.Items.Add(s);
}
}
Just call AddItem and this will invoke the add using a delegate if it is required otherwise it will just add the item directly to the box.
OneSHOT
Just encapsulate adding the text to the listbox to another method:
private void timer1_Tick(object sender, EventArgs e)
{
// ...
AddTextToListBox("\n\n işlem bitti...");
}
private void AddTextToListBox(string text)
{
if(list1.InvokeRequired)
{
list1.Invoke(new MethodInvoker(AddTextToListBox), new object[] { text });
return;
}
list1.Items.Add(text);
}
Can also use lambda notation. So, instead of:
formControl.Field = newValue; //Causes error
Try:
Invoke(new Action(() =>
{
formControl.Field = newValue; //No error
}));
Add this code before starting the thread:
//kolay gelsin kardeş )
CheckForIllegalCrossThreadCalls = false;
thread1.Start();