I am currently working on a homework assignment that I am struggling with. The goal of the program is to:
Create a program that allows users to record and view names of up to 1000 events. The names of the events are to be stored in an array. The names can be stored and viewed sequentially only: I,e, the first time the user presses “Set” to store a name, it would be placed in index 0 of the array; the second time the user stores a name it would be stored in index 1, etc. Similarly, the first time the user presses “View”, the item found in index 0 of the array is shown to the user; the second time the user presses “View”, the item found in index 1 of the array is shown, etc.
When the user presses the “Set” button (btnSet), an event name is inserted into the array in the next free index, sequentially as described above. The name to insert to the array is taken from txtEventName.
When the user presses the button “View” (btnView), the name of the next event to view sequentially (as described above) is shown to the user. The event name is shown to the user in txtName.
I currently have the code:
namespace ArrayHW
{
public partial class Form1 : Form
{
int[] eventsArray;
const int SIZE = 1000;
public Form1()
{
InitializeComponent();
}
private void btnSet_Click(object sender, EventArgs e)
{
eventsArray = new int[SIZE];
for (int index = 0; index < eventsArray.Length - 1; index++)
{
eventsArray[index] = Convert.ToInt32(txtEventName.Text);
}
}
private void btnView_Click(object sender, EventArgs e)
{
for (int index = 0; index < eventsArray.Length- 1; index++)
{
Debug.WriteLine(eventsArray[index]);
txtName.Text = Convert.ToString(eventsArray[index]);
}
}
}
}
When I run the form, I only get the result for index = 0,1, 2, 3, etc or whatever I had just input into the array in
private void btnSet_Click(object sender, EventArgs e)
{
eventsArray = new int[SIZE];
for (int index = 0; index < eventsArray.Length - 1; index++)
{
eventsArray[index] = Convert.ToInt32(txtEventName.Text);
}
}
rather than it showing up in sequential order like it is supposed to. Could anyone show me a better way to approach this problem, or help me find out what I am doing wrong? Thank you very much.
Please read the comments in the code block. Hopefully that will help you resolve your problem.
public partial class Form1 : Form
{
const int SIZE = 1000;
int[] eventsArray = new int[SIZE];
//as per your requirement, you would need these
//to display and set items at proper index in the array.
int _setIndex = 0;
int _viewIndex = 0;
public Form1()
{
InitializeComponent();
}
private void btnSet_Click(object sender, EventArgs e)
{
//this is where your problem is. Every time the Set btn is clicked,
//you are creating a new array. Therefore you are only seeing what you added in the
//last click. Anything that was added to the array on the prior clicks are lost because
//you just created a new array with the line below.
//eventsArray = new int[SIZE];
//You would need to comment the line above because this is code block is being
//executed on every btnSet click. New up this array only once by moving this to global scope.
//for (int index = 0; index < eventsArray.Length - 1; index++)
//{
// eventsArray[index] = Convert.ToInt32(txtEventName.Text);
//}
//Since we have created fields to keep track of _setIndex, all we need to do is:
if (_setIndex < SIZE)
{
eventsArray[_setIndex] = Convert.ToInt32(txtEventName.Text);
_setIndex++;
}
}
private void btnView_Click(object sender, EventArgs e)
{
//this wont be necessary.
//for (int index = 0; index < eventsArray.Length - 1; index++)
//{
// Debug.WriteLine(eventsArray[index]);
// txtName.Text = Convert.ToString(eventsArray[index]);
//}
if(eventsArray.Length > _viewIndex)
{
txtName.Text = Convert.ToString(eventsArray[_viewIndex]);
//this is to fulfill the requirement below:
// Similarly, the first time the user presses “View”, the item found in index 0
// of the array is shown to the user; the second time the user presses “View”,
// the item found in index 1 of the array is shown, etc.
_viewIndex++;
}
}
}
Try this:
int[] eventsArray = new int[SIZE];
int index = 0;
const int SIZE = 1000;
private void btnSet_Click(object sender, EventArgs e)
{
eventsArray[index++] = Convert.ToInt32(txtEventName.Text);
}
Related
I’m a student working on a class project to store string values into an array[10] using a “Store” button. Then the “Display” button will display the string values in the array[10] in a list box. Extra credit if we display the position too.
Currently when I click the “Store” button I do see the message the value was stored. But when I click the “Display” button the list box shows 10 “0”. Every time I make it only makes it worse so I’m not sure what I’m missing and overlooking.
My global variables
string[] results = new string[10];
string value;
I’m using the for loop to take the string value in the “ResultLabel” to store them in the array[10] until all spaces are take, total of 10 values. The “StoreLabel” displays the message that the value was stored.
protected void StoreButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < results.Length; i++)
{
results[i] = ResultLabel.Text.ToString();
}
StoreLabel.Text = "Results have been stored";
}
Then I believe I’m taking the values from the results[10] array and displaying those values in the list box.
protected void DisplayButton_Click(object sender, EventArgs e)
{
DisplayListBox.Items.Clear();
for (int i = 0; i < results.Length; i++)
{
DisplayListBox.Items.Add(results[i].ToString());
}
}
You can append the index to string.
private void StoreButton_Click(object sender, EventArgs e)
{
for (int i = 0; i < results.Length; i++)
{
results[i] = ResultLabel.Text.ToString();
}
StoreLabel.Text = "Results have been stored";
}
private void DisplayButton_Click(object sender, EventArgs e)
{
DisplayListBox.Items.Clear();
for (int i = 0; i < results.Length; i++)
{
DisplayListBox.Items.Add($"{results[i].ToString()} - {i}");
}
}
I understand your project requires you to use an array and to limit it to 10 items. Those requirements might be simplified if we let the ListBox do all the hard work. I'd like to offer an easy way to get strings into the ListBox with the idea that you can then adapt this strategy to meet your project requirements.
The ListBox is simple to work with if we tell it to use our list as the source of the items it displays. Then all we have to do is add an item to this list and tell the ListBox to Refresh() its contents.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
listBoxDisplay.DataSource = Values;
}
// Here is our list of strings
BindingList<string> Values = new BindingList<string>();
private void buttonStore_Click(Object sender, EventArgs e)
{
// We look at the value in the textbox and add it to list...
Values.Add((Values.Count + 1).ToString() + " - " + textBoxValueToAdd.Text);
// …and tell the ListBox to update itself from the list
listBoxDisplay.Refresh();
}
}
I'm generating six numbers, adding them to an array and displaying them in labels, after I attempt to sort the integers and then display them again, all of them return the value "0"
int[] generatedNums = new int[6]; //Array containing generated integers
protected void BtnGenerate_Click(object sender, EventArgs e)
{
Random newRandom = new Random();
for (int i = 0; i < 5; i++)
{
generatedNums[i] = newRandom.Next(1, 50);
}
lblNum1.Text = generatedNums[0].ToString();
lblNum2.Text = generatedNums[1].ToString();
lblNum3.Text = generatedNums[2].ToString();
lblNum4.Text = generatedNums[3].ToString();
lblNum5.Text = generatedNums[4].ToString();
lblNum6.Text = generatedNums[5].ToString();
}
protected void BtnSort_Click(object sender, EventArgs e)
{
Array.Sort(generatedNums);
lblNum1.Text = generatedNums[0].ToString();
lblNum2.Text = generatedNums[1].ToString();
lblNum3.Text = generatedNums[2].ToString();
lblNum4.Text = generatedNums[3].ToString();
lblNum5.Text = generatedNums[4].ToString();
lblNum6.Text = generatedNums[5].ToString();
}
I combined both methods into one and it works fine, any help?
Your problem is that you're forgetting that the web server doesn't preserve the state of the generatedNums array between requests. Web Forms, like most web frameworks, is stateless. When you attempt to sort the array, you will need to regenerate the list or read it out of the labels. Your class members are not persisted between requests.
you only initialize values 0 - 4
for (int i = 0; i < 5; i++)
but you display 0 - 5
lblNum1.Text = generatedNums[0].ToString();
lblNum2.Text = generatedNums[1].ToString();
lblNum3.Text = generatedNums[2].ToString();
lblNum4.Text = generatedNums[3].ToString();
lblNum5.Text = generatedNums[4].ToString();
lblNum6.Text = generatedNums[5].ToString();
It would also help if you showed the declaration generatedNums
Ahh this being a web server is an extremely important detail
and you can keep the variable from clearing like this
private int[] generatedNums
{
get { return (int[])HttpContext.Current.Session["generatedNums"]; }
set { HttpContext.Current.Session["generatedNums"] = value; }
}
in your constructor or initializer you can add this
if (generatedNums == null)
generatedNums = new int[6];
or better you can set it upon starting up the server
count in initially 0.
array list contain 3 questions at 0 1 2 index.
using click event on button it shows only the 0 index value whenever i click on button.
i want that whenever i click on button array index incremented and show the next question.
public void Button1_Click(object sender, EventArgs e)
{
if (count != 3)
{
lbl_question.Text = question_list[count].ToString();
rdb_op1.Text = op1_list[count].ToString();
rdb_op2.Text = op2_list[count].ToString();
rdb_op3.Text = op3_list[count].ToString();
rdb_op4.Text = op4_list[count].ToString();
count = count + 1;
}
declare a static variable so that it doesn't reset when you load the page
public static int count { get; set; }
and then use it in your event
public void Button1_Click(object sender, EventArgs e)
{
if (count != 3)
{
lbl_question.Text = question_list[count].ToString();
rdb_op1.Text = op1_list[count].ToString();
rdb_op2.Text = op2_list[count].ToString();
rdb_op3.Text = op3_list[count].ToString();
rdb_op4.Text = op4_list[count].ToString();
count = count + 1;
}
else
{
count = 0;
}
i M declaring an int type array and trying to print all its elements but it prints only last element .....give me the right code.....
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
int[] arr;
int range;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
range = Convert.ToInt32(textBox1.Text);
arr = new int[range];
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < range; i++)
{
arr[i] = Convert.ToInt32(textBox2.Text);
}
}
private void button1_Click(object sender, EventArgs e)
{
for(int i =0;i<range;i++)
{
textBox3.Text = textBox3.Text + arr[i].ToString();
}
}
}
}
This line: arr[i] = Convert.ToInt32(textBox2.Text); will set every element in the array to the value in textbox2. Is that your intent?
Int arrays are common. They store many integer values. And these values can be used in many ways. This introductory material covers int arrays, showing declarations, assignments, elements, loops and methods.please see here
this code is simple example that work array int
using System;
class Program
{
static void Main()
{
int[] arr1 = new int[] { 3, 4, 5 }; // Declare int array
int[] arr2 = { 3, 4, 5 }; // Another
var arr3 = new int[] { 3, 4, 5 }; // Another
int[] arr4 = new int[3]; // Declare int array of zeros
arr4[0] = 3;
arr4[1] = 4;
arr4[2] = 5;
if (arr1[0] == arr2[0] &&
arr1[0] == arr3[0] &&
arr1[0] == arr4[0])
{
Console.WriteLine("First elements are the same");
}
}
}
using System;
class Program
{
static void Main()
{
// Loop over array of integers.
foreach (int id in GetEmployeeIds())
{
Console.WriteLine(id);
}
// Loop over array of integers.
int[] employees = GetEmployeeIds();
for (int i = 0; i < employees.Length; i++)
{
Console.WriteLine(employees[i]);
}
}
/// <summary>
/// Returns an array of integers.
/// </summary>
static int[] GetEmployeeIds()
{
int[] employees = new int[5];
employees[0] = 1;
employees[1] = 3;
employees[2] = 5;
employees[3] = 7;
employees[4] = 8;
return employees;
}
}
Output
1
3
5
7
8
1
3
5
7
8
Is textBox2.Text one number, or a sequence of numbers? If it is, for example, 1,2,3 then you'll have to Split the string on , and then convert each entry of the String[] you get back to an integer, and store those in the array.
I am not sure what you are trying to do.
It appears that you are reading an input from a textbox whenever it is changed
and recreating the array to the size indicated in that textbox.
The second textbox fills the array whenever it is changed to whatever the second
textbox accepts as input (this makes no sense at all).
button1 displays array as a string, which is probably alright.
You might want to change the 2nd textbox into a button which fills the array.
Otherwise, rethink your intent of 2nd textbox, it makes no sense.
Where do you clear textBox3.Text ?
You are accumulating in this text box. When you do that, and the input overflows, you will only see the last thing added. Perhaps this is the problem. I might tweak:
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = "";
for(int i =0;i<range;i++)
{
textBox3.Text = textBox3.Text + arr[i].ToString();
}
}
Hi i am having a problem here. So you can see whenever the txtBtn0 and txtBtn1 is clicked it increments its own array which is then used for squareChecked string. But what I want to do first is to give out an error message if txtBtn0 nor txtBtn1 is not clicked. But it does not pop up anything.
public partial class MainForm : Form
{
public int[] clickNumBoxArray = Enumerable.Repeat(1, 81).ToArray();
public MainForm()
{
InitializeComponent();
} ... ... ...
private void btn1_Click(object sender, EventArgs e) {
UserSquare checkClickedBox = new UserSquare();
string checkClickBox = checkClickedBox.squareChecked();
if (checkClickedBox == null) {
MessageBox.Show("You did not enter any text on the form");
}
}
private void txtBtn1_Click(object sender, EventArgs e) {
clickNumBoxArray[1]++;
if (clickNumBoxArray[1] % 2 == 0) {
txtBtn1.BackColor = System.Drawing.Color.DarkOrange;
} else {
txtBtn1.BackColor = System.Drawing.Color.WhiteSmoke;
}
}
private void txtBtn0_Click(object sender, EventArgs e) {
clickNumBoxArray[0]++;
if (clickNumBoxArray[0] % 2 == 0) {
txtBtn0.BackColor = System.Drawing.Color.DarkOrange;
} else {
txtBtn0.BackColor = System.Drawing.Color.WhiteSmoke;
}
}
This is the other class
class UserSquare {
public string squareChecked() {
string clickedBoxes = null;
MainForm numBoxArray = new MainForm();
int[] clickNumBoxArray = numBoxArray.clickNumBoxArray;
for (int i = 0; i < 81; i++) {
if (clickNumBoxArray[i] % 2 == 0) {
clickedBoxes += "txtBtn" + i + ", ";
}
} return clickedBoxes;
}
The line:
for (int i = 0; i < 81; i++)
should be:
for (int i = 0; i < 80; i++)
The array clickNumBoxArray only had 80 elements, indices 0 to 79. You're looping through 81 items, indices 0 to 80.
About IndexOutOfRange Exception Your problem is that you implement your list here
public int[] clickNumBoxArray = Enumerable.Repeat(1, 80).ToArray();
as starts from 1 and finished 80 = 80 elements
but in method your for loop starts from 0 and finished 81 = 81 elements
and about controlling by error.. simply and tricky.. you can implement an internal / public boolean as default false and set to true in a mouse event as you need (i.e.mouseclick event)..end of your error method or where you need else, set to back false to be ready for another click-event controlling
About ButtonClick not fire its event (if im not misunderstood) : Did you deleted your some methods of buttons ? could you been forgot to implement it back ?
open your design mode click once onto your controls which you want to check, and then open properties => events.. if your events implemented then it should be as so : (i.e.)
(property) MouseClick (value) Button1_MouseClick
I fixed it by moving
public int[] clickNumBoxArray = Enumerable.Repeat(1, 81).ToArray();
to UserSquare class. I figured it out that UserSquare class only gets the value when program is run but not updating.