How to get array data from one Click Method to another one - c#

Don't think i could be any newer to coding, so please forgive me for whats about to be asked.
Im currently writing a program that lets the user enter a desired amount of random numbers to be generated by Random via textBox (lets say 15 --> you get 15 random numbers), ranging from 1 to 1000.
When hitting the Button A, those randomized Numbers will be saved in Zahlenarray[](-->with the length of the number entered in the textbox) and displayed in label1.Text.
Then there's a Button B, that, when clicked, should sort the Numbers from Zahlenarray[] via bubblesort and display them in label2.
My problem is now that the second Method (Button B_Click) doesnt have the contents of Zahlenarray from the Button A_Click Method.
Id like to pass this data by ref via the arguments, but fiddling with public void (Object sender, EventArgs e) seems to get me in major trouble.
Can i add arguments after EventArgs e, ... or am i missing another way of getting data out f this "scope" (hope thats the right word)?
Both Methods are in the same class.
part of the code of Button A:
public void Button_Anzeigen_Click(Object sender, EventArgs e)
{
label1.Text = "";
int[] Zahlenarray = new int[Int32.Parse(textBox1.Text)];
Everything from Button B:
private void Button_Sortieren_Click(object sender, EventArgs e)
{
label2.Text = "";
label3.Text = "";
int Speicher;
for (int n = Zahlenarray.Length; n > 0; n--)
{
for (int i = 0; i < n-1; i++)
{
if (Zahlenarray[i] > Zahlenarray[i + 1])
{
Speicher = Zahlenarray[i];
Zahlenarray[i] = Zahlenarray[i + 1];
Zahlenarray[i + 1] = Speicher;
Speicher = 0;
}
}
}
foreach (int i in Zahlenarray)
{
label2.Text += i + " ";
if ((i % 9 == 0) && !(i == 0))
label2.Text += "\n";
}
}

Put your array declaration outside of your buttona click handler so you can reference it inside your button b handler.
int[] Zahlenarray;
public void Button_Anzeigen_Click(Object sender, EventArgs e)
{
label1.Text = "";
Zahlenarray = new int[Int32.Parse(textBox1.Text)];
...
}

Related

How to sum all numbers in a Listbox using TextBox?

I want to count and sum all values in a ListBox. For example, I have the following values in my ListBox: 4, 6, 1, 7. My current value is 18. If I add a 2 with a TextBox, I need to get 20 and if I add 5 I need to get 25 in total.
If I try it with the below code, it gives me a whole other number.
Here is my code:
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
You missed to initialize default value of sum. Assign sum = 0 before adding values to sum variable
private void AddButton_Click(object sender, EventArgs e)
{
decimal sum = 0; //Set sum = 0 by default
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
for (int i = 0; i < listBox2.Items.Count; i++)
{
//To check value of sum after each iteration, you can print it on console
Console.WriteLine("Sum =" +sum);
sum += Convert.ToDecimal(listBox2.Items[i].ToString());
}
Label1.Text = sum.ToString();
}
Sorry for maybe not answer but it is strange that your compiler didn't tell you to initialize sum. The second I tested your code and it works correctly as expected that means that if the problem is not in sum variable then you made something else to this fields somewhere else so your code doesn't work correctly.
Having in mind your comment to previous person I'd say the same. In some cases (I know it's funny but) you may have viruses on your computer. Check it. Once in my life I've failed my maths lab work because of virus that interrupted my program so it drew the wrong chart !sick I know :D
private void button1_Click(object sender, EventArgs e)
{
var sum = 0;
var value = 0;
listBox1.Items.Add(textBox1.Text);
foreach (var item in listBox1.Items)
{
if (!int.TryParse(item.ToString(), out value))
continue;
sum = sum + value;
}
label1.Text = sum.ToString();
textBox1.Text = string.Empty;
}
Use of unassigned local variable 'sum', sum must be assigned before use !
decimal sum = 0;
Rest all is ok
Need to set sum to 0 and also it is probably best to use a foreach instead of a Dotloop.
private void AddButton_Click(object sender, EventArgs e) {
decimal sum = 0;
listBox2.Items.Add(TextBox1.Text);
TextBox1.Text = "";
foreach (string s in listBox2) {
sum += Convert.ToDecimal(s);
}
Label1.Text = sum.ToString();
}

Fill a textbox based on another textbox text

I have TextBoxA and TextBoxB. What i want to do is , whenever i put a number (yes, both of the textboxes values are always integers) in TextBoxA , TextBoxB should "autocomplete" with value (100-TextBoxA). Same thing goes for TextBoxB. The sum of TextBoxA and TextBoxB should always be 100.
Here's what i've already tried:
static void TextBoxA_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-a).ToString();
TextBoxB.Text = text;
}
Static void TextBoxB_TextChanged()...
{
int a = Convert.ToInt32(TextBoxA.Text);
int b = Convert.ToInt32(TextBoxB.Text);
string text = (100-b).ToString();
TextBoxA.Text = text;
}
But it doesn't work.
Here's what you can try:
private void TextBoxA_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxA.Text, out num))
{
string text = (100 - num).ToString();
TextBoxB.Text = text;
}
}
private void TextBoxB_TextChanged(object sender, EventArgs e)
{
int num = 0;
if (int.TryParse(TextBoxB.Text, out num))
{
string text = (100 - num).ToString();
TextBoxA.Text = text;
}
}
This will autocomplete on either TextBox on TextChanged Event.
First, i dont know why your event handlers are declared static.. its usually got to be :
private void TextBoxA_TextChanged(object sender, EventArgs e) { }
Secondly, you know if you have 2 textboxs, and each one triggers the other, you'll never go out of the TextChanged event.
To understand me more, here's an example :
1- You set TextBoxB.text = "1";2- TextBoxB.TextChanged triggers, it
sets TextBoxA.Text = "2"; 3- TextBoxA.TextChanged triggers, it sets
TextBoxB.Text = "1";
And it continues like this until i believe you'll get an Exception of memory.
EDIT : The opertator '-' works on numbers. You can't substract a number from a string. they have to be both numbers, so convert them first.
EDIT 2 :
Here's a code i wrote that works fine
private void textBox1_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox1.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox2.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox2.Text = m.ToString();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int n;
if (int.TryParse(textBox2.Text, out n)) // Check if the text value is a number
{
if (n > 100) // Since you want a sum of 100
return;
int m = 100 - n; // remaining
if (textBox1.Text != m.ToString()) // to not re-trigger the TextChanged event
textBox1.Text = m.ToString();
}
}
Try this. This is a more efficient and elegant way I'd choose using lambda expressions, without repeating the method:
private void onChangeDoSum(object sender, EventArgs e,
TextBox substractNumber, TextBox sumNumber)
{
sumNumber.Text = (100 - Int32.Parse(substractNumber.Text)).ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox1, textBox2);
textBox2.TextChanged += (a, b) => onChangeDoSum(sender, e, textBox2, textBox1);
}
Alternatively use Int32.TryParse to prevent unexpected results.
I think you can do something like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = (100 - Int32.Parse(textBox1.Text)).ToString();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = (100 - Int32.Parse(textBox2.Text)).ToString();
}
when I see that static word I think you have tried to create these method by yourself and you forgot to add
textBox1.TextChanged += textBox1_Changed;
// I saw other post where you wrote that it could raise exception and fall. Of course it can. You can use if condition like
textBox1.Text != null && textBox1.Text != ""
before value would be changed or TryParse() method

C# - I can't seem to have the results of the square of 10 numbers displayed on a label in a windows Form line by line

I have a window form application with a button and a label.
After a push of the button, the label needs to display the square of the numbers 1 till 10. This needs to be displayed line by line.
This is the code I have so far:
private void button1_Click(object sender, EventArgs e)
{
int[] sqrNumbers = new int[10];
for (int i = 1; i != sqrNumbers.Length; i++)
{
sqrNumbers[i] = i * i;
lblSquares.Text = (sqrNumbers[i]).ToString()+ Environment.NewLine;
}
Unfortunately this doesn't work. As I am new to programming, I can't seem to figure this out. I scoured the net to find an answer bt haven't found what I was looking for. Thanks for helping me out on this.
Kr,
Jay
Try this instead: (Edit this is probably safer)
private void button1_Click(object sender, EventArgs e)
{
int[] sqrNumbers = new int[10];
String text = "";
for (int i = 1; i != sqrNumbers.Length; i++)
{
sqrNumbers[i] = i * i;
text += (sqrNumbers[i]).ToString()+ Environment.NewLine;
}
lblSquares.Text = text;
}
lblSquares.Text = (sqrNumbers[i]).ToString()+ Environment.NewLine;
overwrites the value of lblSquares.Text
lblSquares.Text += (sqrNumbers[i]).ToString()+ Environment.NewLine;
Will preserve the value and add to it.
https://msdn.microsoft.com/en-us/library/sa7629ew.aspx

c# windows form application dynamic objects value

i have made a mistake of re-inventing the wheel. There are options
but somehow i like the feel of this.
Sorry but don't have enough rep to post an image.
This is how the form looks like:
SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels
[ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons
I've got the 'new' button click event to generate a row, and serial number to be automatic
and inserted the items into the collections from Properties panel.
Delete button deletes an entire row and shifts both the button up on Y position.
I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes,
for which i have the code as :
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
calculate_quant(this, e);
quanty = result;
}
public static string result;
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
TextBox quan;
quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
result = quantity.ToString();
quan.Text = result;
}
return result;
}
count is initialized at 1 on form load, keeps increasing with number of rows
the same code works in the delete row method
public void delete_row(object sender, EventArgs e) //function to delete a row
{
TextBox snum;
snum = (TextBox)this.Controls.Find("SNO"+count, true)[0];
snum.Dispose();
...//delete other row elements
}
please help me figure out why it doesnt work for the print_quant / calculate_quant methods
I made some changes to your code. I changed the return on your calculate method to a string, and added a quanty.Text=calculatemethod line to your print method
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
//add this line
quanty.Text = calculate_quant(this, e).ToString();
}
public static string result;
//change this
//public void calculate_quant(object sender, EventArgs e)
//to
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
//this isn't being used here
//TextBox quan;
//quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
return quantity.ToString();
}
}
Edit
try this.
Create a usercontrol and make it look exactly like one of your rows.
add a property variable for each of the boxes
//whenever you Sno="something" the textbox will automatically be updated.
private string _Sno="00000";
public string Sno{get{return _Sno;}set{_sno=value; SnoTextBox.Text=value;}}
do this for each of your textboxes.
on your main form now you can add a flowpanel, they a bit tricky at first. when you add your new Usercontrol to it, they will automatically be added from the top down, or up, or however you set it up.
When you want to add a new row, just add your new Usercontrol to the flowpanel
FlowPanel flowPanel =new FlowPanel();
FlowPanel.Controls.Add(new myUserControl());
to delete
FlowPanel.Controls.RemoveAt(2);
This is really poorly written, but I am out of time. Either ignore me altogether, or try to figure it out. Sorry I couldn't be more help.
this worked for me
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox quant;
int x = count - 1;
string num = Convert.ToString(x);
quant = (TextBox)this.Controls.Find("QUANTITY" + x , true)[0];
TextBox to = (TextBox)this.Controls.Find("STO" + x, true)[0];
TextBox from = (TextBox)this.Controls.Find("SFRM" + x, true)[0];
string tovalue = to.Text;
int to1 = Convert.ToInt32(tovalue);
string fromvalue = from.Text;
int from1 = Convert.ToInt32(fromvalue);
int result = (to1 - from1) + 1 ;
if (result > 0)
{
string result1 = Convert.ToString(result);
quant.Text = result1;
}
}
after adding
STO.TextChanged += new System.EventHandler(textBox_TextChanged);
at the function that was generating the boxes where i needed to calculate :)

Converting strings to int in C#

im pretty new to C# and i want to make a cardgame. What i have is a list of cards (strings) with names like c6, s3, h11, d13 where the character represents the colour and the number represents the value. When pressing a button the program takes a random string from the list and displays it in a textbox. From there the point of the game is to guess if the next random card will have a higher value or a lower value then the previous card.
What i want to do is to take the string from the textbox and turn it into a int so that i can compare the value of the previous card with the new one. Only problem is how do i get rid of the c in c6 so i can convert it by using parse.
This is my code.
public partial class MainWindow : Window
{
static Random rndmlist = new Random();
Random rndm = new Random();
List<string> deck = new List<string>();
int score = 0;
public MainWindow()
{
InitializeComponent();
}
private void test_Click(object sender, RoutedEventArgs e)
{
//disregard this
foreach (string j in deck)
{
testbox.Text += j + ", ";
}
}
private void btnstart_Click(object sender, RoutedEventArgs e)
{
//this is where i add all the cards to the list
for (int i = 1; i <= 13;)
{
deck.Add("c" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("s" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("h" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("d" + i);
i++;
}
}
private void btnbegin_Click(object sender, RoutedEventArgs e)
{
//this is where i take a random card from the list and display it in textBox2
int r = rndmlist.Next(deck.Count);
textBox2.Text = ((string)deck[r]);
//disregard this
testbox.Text += ((string)deck[r]) + ", ";
deck.Remove((string)deck[r]);
}
private void btnhigh_Click(object sender, RoutedEventArgs e)
{
//this is where i want to compare the cards.
}
}
Thank you in advance for reading this. (:
I'd better create a class Card, which represents a card, with 2 properties: Color and Number and implemented method Card.ParseFromString()
Try this,
string SubString = MyString.Substring(1);
But take care if the string is empty, it is an error case.
Assuming there will always be one (and only one) character before the number, you can simply do this:
string numberAsString = "c2".Substring(1);
And to make that an int:
int number = Int32.Parse(numberAsString);
You can use Regex to replace all alpha characters eg
string result = Regex.Replace(myString, #"[a-zA-Z\s]+", string.Empty);
string str = "c12";
var noChars = str.SubString(1); // take a new string from index 1
var number = Int32.Parse(noChars);

Categories

Resources