How to store user input in a 2D array? - c#

So I have this GUI application that is supposed to calculate shipping costs. First I need to enter the number of packages that is being shipped (already done), then choose package # from a domainUpDown tool(also complete), and then input dimensions for selected package in a text box. This is where I'm stuck. This is what I have thus far.
const int WEIGHT = 0
const int NMBR_OF_PROPETIES = 7;
const int MAX_PACKAGES = 10;
const double FLAT_RATE = 4.99;
int numOfPackages, packageNumber;
double[,] packagesArray = new double[MAX_PACKAGES, NMBR_OF_PROPETIES];
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//label texts get initialized
}
private void button1_Click(object sender, EventArgs e)
{
if (!int.TryParse(numOfPackagesTextBox.Text, out numOfPackages))
{
//message box tells that number cant be parsed
}
else if(numOfPackages > 0 && numOfPackages < 10)
{
//everything in the program is enabled
}
else
{
//message box saying that you can't ship more than 10 packages
}
//adding package numbers to the domainUpDown tool
DomainUpDown.DomainUpDownItemCollection items = packageUpDown.Items;
for (int packageNumber = 1; packageNumber <= numOfPackages; packageNumber++)
{
items.Add(packageNumber);
}
}
private void weightBox_TextChanged(object sender, EventArgs e)
{
packagesArray[(int)packageUpDown.SelectedItem, WEIGHT] = Convert.ToInt32(weightBox.Text);
//also here goes the rest of the dimension entry
}//from here i don't know what to do, and im sure that this isn't right..
The thing I'm confused about is how to save entered text if user somehow changes package number from domainUpDown tool.

Have you tried registering to the OnChanged or SelectedItemChanged events of the DomainUpDown ?
Perform saving on the OnChanged event handler.
Example:
myDomainUpDown.OnChanged += new EventHandler(myDomainUpDown_OnChanged);
void OnChanged(object sender, EventArgs e)
{
//save all the information you need in whatever collection/file/db you want
}

Related

Parsing int does not work for some odd reason

I have a second form that pops up upon clicking a button, a user can input some parameters for a method, save the input within a variable, and then I parse the result to an int ( thus so I can utilize it within my method ). Now, upon parsing it, the value appears to be NULL as oppose to what the user inputted within the textboxes.
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int i = 0;
while (i == 0)
{
if (form.click) // ok button is clicked
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
goto break_0; // break out of loop ( loop is to check when button is clicked )
}
}
}
}
As you can see here, the values that the user inputs is Height,Width and Framerate respectively. It parses it to an int, as I explained, and stores it in the displayproperties int array.
This is the second form:
public string Height { get; set; }
public string Width { get; set; }
public string Framerate { get; set; }
public bool click = false;
public Form2()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e){}
private void textBox1_TextChanged(object sender, EventArgs e)
{
Height = height.Text;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
Width = width.Text;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
Framerate = framerate.Text;
}
public void OK_Click(object sender, EventArgs e)
{
click = true;
}
Ultimately, the values are then passed into this class:
public Class1(int width, int height)
However I get an out of range exception saying the value must be greater than zero. Goes without saying, the values I inputted were certainly greater than zero ( 800, 600, 60 respectively ) where 60 is used elsewhere.
Since my comment suggestion worked for you, I'll add it as an answer.
From what you've said, it sounds likely that you're not setting DialogResult anywhere, so your if statement is never being entered because the condition isn't met.
You should set the dialog result and close the form in OK_Click:
public void OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
And then you should remove the extra code from your main form:
var displayproperties = new int[3];
using (Form2 form = new Form2())
{
try
{
if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// parse values
displayproperties[0] = int.Parse(form.Height);
displayproperties[1] = int.Parse(form.Width);
displayproperties[2] = int.Parse(form.Framerate);
}
}
}
The dialog result will serve as your click property so this is no longer required. By the way, I recommend switching to TryParse instead so that you can actively check if the input values are valid integers, as opposed to leaving it until exceptions are thrown.
An example of this:
string a = "hello"; // substitute user input here
int result;
if (!int.TryParse(a, out result))
{
MessageBox.Show($"{a} isn't a number!");
return;
}
MessageBox.Show($"Your integer is {result}");
If you're newish to programming, I recommend getting familiar with how to use the debugger. Setting a breakpoint and inspecting values as you stepped through the code would have revealed where the problem was very quickly. Microsoft have a tutorial for this.

C# What am I doing wrong? Attempting counter up with do while loop but only iterating once

Help, I'm a novice programming student who got assigned a side task at work; This is the pseudo code I wrote for it:
Write a program with 3 buttons:
Exit/Close, Clear/Reset, Count/Calculate
When the user clicks the count button, the number displayed in the label/textbox should increase by 1 and this should continue infinitely.
When the user clicks the clear/Reset button, the number displayed in the label/textbox should be reset to 0.`{
Application.Exit();
}
private void btnCount_Click(object sender, EventArgs e)
{
int Count = 1;
int Numberdisplayed;
{
do Count++;
while (Count >= 1);
Numberdisplayed = Count + 1;
lblNumberdisplayed.Text = Numberdisplayed.ToString();
}
}
private void btnReset_Click(object sender, EventArgs e)
{
int Count = 0;
lblNumberdisplayed.Text = String.Empty;
lblNumberdisplayed.Text = Count.ToString();
}
}
`
When the user clicks the Exit/Close btn, the application should close.
The only language I am familiar with is c# hence my writing it here and my company runs windows for all end users so I figured why not.
private void btnExit_Click(object sender, EventArgs e)
The code I have so far Image
If you aren't bound to use While loop you can try using session or the below:
private int count;
protected void btnCount_Click(object sender, EventArgs e)
{
count = Int32.Parse(lblCount.Text);
count++;
lblCount.Text = count.ToString();
}
Note: Though not tested, you can try the above.
I think the issue is the Count variable is local to the method, thus the do while never sees the reset.

Resume Count in IsolatedStorageSettings

When I press the button count the number perfectly, but when you exit the application and return to count starts counting again and not when the number that was saved in IsolatedStorageSettings!!
How can I make it when the counting of the number that was saved in IsolatedStorageSettins?
(I use Windows phone 8.1 silverlight)
IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
int Points;
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += Page2_Loaded;
}
private void Page2_Loaded(object sender, RoutedEventArgs e)
{
if (setting.Contains("save"))
{
PointsText.Text = setting["save"].ToString();
}
}
private void Counts_Click(object sender, RoutedEventArgs e)
{
Points = Points + 1;
setting["save"] = Points;
PointsText.Text = setting["save"].ToString();
}
}
According to your code Points will always initialize to 0 when the page loads and when you click count it will increment from 0. You need to load the count from appsettings and put it into Points
private void Page2_Loaded(object sender, RoutedEventArgs e)
{
if (setting.Contains("save"))
{
//Initialize Points with the value from settings
Points = int.Parse(setting["save"].ToString());
PointsText.Text = Points.ToString();
}
}

How to print an array in forms (C#)

I have a mathematical problem and I´m trying to solve it, the problem is that you have 81 coins, but one is fake and it´s heavier than the others,you have to find out which one is the fake one by using a scale and doing only 4 comparisons.
I´m trying to make it like a game, when a users decides which coin will be the fake one, and the other player has to find it.
I made an array named monedasf and made all the values 0, so when the users type in the coin that wants to be the fake one, the value changes to 1. I´m trying right now to print the array, but I don´t know if I have to print it in a multiline textbox or where, here´s the code I have untill now.
public partial class Form1 : Form
{
public static int[] monedasf = new int[81];
public Form1()
{
InitializeComponent();
for( int i = 0; i<=80;i++)
{
monedasf[i] = 0;
}
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click_1(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
monedasf[n] = 1;
textBox1.Clear();
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 80; i++)
textBox2.Text = Convert.ToString(monedasf[i]);
}
}
I have only BASIC KNOWLEDGE of programming, that´s why my code might be so primitive :D
Try using something like this:
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 80; i++)
textBox2.Text += monedasf[i].ToString() + " ";
}
If you want you can replace " " with any separator you want, like "\n" for newline.
Actually your code would work too, the problem is you were reseting textBox2's text by using assign operator:
textBox2.Text = Convert.ToString(monedasf[i]); // will clear and then print
textBox2.Text += Convert.ToString(monedasf[i]); // will not clear and print
All you need is not to reset previous text inside.
private void button2_Click(object sender, EventArgs e)
{
textBox2.Text = string.Join(", ", monedasf);
}
Use string.Join which is very useful for display.

C# - Updating a Chart in Real-Time

Bear with me, I'm new to Stack Overflow, but have used it as a resource for a long time when researching methods of programming that I'm not fond with.
I read up a tutorial on how to create a graph in a C# Windows Forms Application, and was attempting to find out how to make it update itself in real-time if I ever need to use the graph to plot the total amount of data in a sensor. To test it out, I'm using a timer, ticking at every second (1000ms). And before I can use this with a sensor, I'm having two values automatically increment by 1.
The current problem I'm facing is that the chart itself won't update, and only stays the way it was drawn when the form loaded. I thought it was because I have to redraw the chart with chart1.Update();, and I tried using that before/after recreating the chart every second. However, the result is the same regardless. I just wondered if there's something I haven't done or needs to be changed in order to update the chart in real-time.
This is where the code is at currently:
public partial class Form1 : Form
{
int a = 1;
int b = 2;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Data arrays.
string[] seriesArray = { "Cats", "Dogs" };
int[] pointsArray = { a, b };
// Set palette.
this.chart1.Palette = ChartColorPalette.SeaGreen;
// Set title.
this.chart1.Titles.Add("Pets");
// Add series.
for (int i = 0; i < seriesArray.Length; i++)
{
// Add series.
Series series = this.chart1.Series.Add(seriesArray[i]);
// Add point.
series.Points.Add(pointsArray[i]);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
a++;
b++;
// Data arrays.
string[] seriesArray = { "Cats", "Dogs" };
int[] pointsArray = { a, b };
// Set palette.
this.chart1.Palette = ChartColorPalette.SeaGreen;
// Set title.
this.chart1.Titles.Add("Pets");
// Add series.
for (int i = 0; i < seriesArray.Length; i++)
{
// Add series.
Series series = this.chart1.Series.Add(seriesArray[i]);
// Add point.
series.Points.Add(pointsArray[i]);
}
chart1.Update();
}
}
Your code has several problems:
The timer click event is not hooked up. I know that it isn't because otherwise you'd get an exception telling you that..
..you can add a series only once. You were doing it on each timer.Tick. This and all other setup commands should go into an initial method like the form load.
I have corrected the errors in the code below, but, obviously, the data don't make any sense yet.
Also: While I have added code to hook up the timer.Tick, the button.Click is not hooked up. Usually you let the designer do this by double-clicking the control to hook up the standard event of a control or by double-clicking the event in the control's event tab in the property page.
int a = 1;
int b = 2;
string[] seriesArray = { "Cats", "Dogs" };
private void Form1_Load(object sender, EventArgs e)
{
// Set palette.
this.chart1.Palette = ChartColorPalette.SeaGreen;
// Set title.
this.chart1.Titles.Add("Pets");
// Add series
this.chart1.Series.Clear();
for (int i = 0; i < seriesArray.Length; i++)
{
chart1.Series.Add(seriesArray[i]);
}
// hook up timer event
timer1.Tick += timer1_Tick;
}
private void timer1_Tick(object sender, EventArgs e)
{
a++;
b++;
// Data array
int[] pointsArray = { a, b };
for (int i = 0; i < seriesArray.Length; i++)
{
// Add point.
chart1.Series[i].Points.Add(pointsArray[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Start();
}

Categories

Resources