C# Array is empty after using Array.Sort() - c#

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

Related

C# Array input from windows form textbox

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);
}

How to store the number form 9 different textbox and sort acceding

This button is populate which means click on this button will auto generate random numbers .
This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int rid = RandomNumber(-111, 999);
int rid1 = RandomNumber(-111, 999);
int rid2 = RandomNumber(-222, 888);
int rid3 = RandomNumber(-333, 777);
int rid4 = RandomNumber(-222, 777);
int rid5 = RandomNumber(-333, 444);
int rid6 = RandomNumber(-555, 888);
int rid7 = RandomNumber(444, 999);
int rid8 = RandomNumber(111, 222);
int rid9 = RandomNumber(222, 333);
txt1.Text = rid.ToString();
txt2.Text = rid1.ToString();
txt3.Text = rid3.ToString();
txt4.Text = rid4.ToString();
txt5.Text = rid5.ToString();
txt6.Text = rid6.ToString();
txt7.Text = rid7.ToString();
txt8.Text = rid8.ToString();
txt9.Text = rid9.ToString();
}
The second button is sort list.
How to take all the numbers and follow acceding to put back in the 9 different textbox ?
This is the coding for button sortlist:
protected void Button2_Click(object sender, EventArgs e)
{
int no1;
int no2;
int no3;
int no4;
int no5;
int no6;
int no7;
int no8;
int no9;
//int answer;
no1 = int.Parse(txt1.Text);
no2 = int.Parse(txt2.Text);
no3 = int.Parse(txt3.Text);
no4 = int.Parse(txt4.Text);
no5 = int.Parse(txt5.Text);
no6 = int.Parse(txt6.Text);
no7 = int.Parse(txt7.Text);
no8 = int.Parse(txt8.Text);
no9 = int.Parse(txt9.Text);
int[] a = new int[] {no1,no2,no3,no4,no5,no6,no7,no8,no9 };
Array.Sort(a);
foreach (var str in a)
{
MessageBox.Show(str.ToString());
}
}
I can display sort ACS in MessageBox but I can't put the number ACS into textbox
But still can't get the answer, where was wrong?
Thank you for help.
You could throw the generated numbers into a list, sort the list and assign the numbers accordingly. Thus, txt1.Text = sortedRandList[0]; and so on for the rest.
To get slightly cleaner code, you could consider also throwing all the text boxes within a list, and eventually end up doing textBoxesList[i] = sortedRandList[i];. That should clean up the code a little bit.
You can create List of ints and then sort it like this :
List<int> rids = null;
protected void Button1_Click(object sender, EventArgs e)
{
rids = new List<int>()
{
RandomNumber(-111, 999),
RandomNumber(-111, 999),
RandomNumber(-222, 888),
RandomNumber(-333, 777),
RandomNumber(-222, 777),
RandomNumber(-333, 444),
RandomNumber(-555, 888),
RandomNumber(444, 999),
RandomNumber(111, 222),
RandomNumber(222, 333)
};
DisplayValues(); // use it if you want to show your values in UI
}
protected void sortButton_Click(object sender, EventArgs e)
{
rids.Sort();
DisplayValues()
}
private void DisplayValues()
{
for (int i = 0; i < Controls.Count; i++)
{
if (Controls[i] is TextBox) if(Controls[i]).ID.Contains("txt"))
(Controls[i] as TextBox).Text = rids[Int32.Parse(Controls[i].ID.Replace("txt", "")) - 1].ToString();
}
}

Stuck with two dimensional array

I'm trying to create a booking service and I've been stuck on this part for many hours and I just can't figure out what I'm doing wrong.
So I've got a Two Dimensional array and when trying to print out some stuff when testing and trying to figure out what's wrong, all I get is System.String[] which doesn't really make me any wiser. I want to be able to access the details in i.e. m_nameMatrix[0,0] to check whether the seat is reserved or not.
Here's a snippet from my form code:
private void UpdateGUI(string customerName, double price)
{
string selectedItem = cmdDisplayOptions.Items[cmdDisplayOptions.SelectedIndex].ToString();
rbtnReserve.Checked = true;
lstSeats.Items.Clear();
lstSeats.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}
And here are two methods from my 2nd class:
public string[] GetSeatInfoStrings(string selectedItem)
{
int count = GetNumOfSeats(selectedItem);
if (count <= 0)
{
return new string[0];
}
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= count; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string seatInfo = m_nameMatrix.GetValue(row, col).ToString();
return seatInfo;
}
I'm not actually getting an exception so it might be my logical thinking that's been taking a hit due to hours and hours of trying to figure it out.
EDIT:
public void ReserveSeat(string name, double price, int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string reserved = string.Format("{0,3} {1,3} {2, 8} {3, 8} {4,22:f2}",
row + 1, col + 1, "Reserved", name, price);
m_nameMatrix[row, col] = reserved;
}
This line:
for (int index = 0; index <= count; index++)
should be:
for (int index = 0; index < count; index++)
Why? Lets say I have an array with 2 objects in it. count would be 2. However, the indexes are 0 and 1. So you have to use a less than operator.
If you're getting "System.String[]" in your messagebox, it's because you're trying to print a string[] directly, rather than the various strings it contains:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(data);
Instead, you need to show the contents of data:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(string.Join("\n", data));
See here for the documentation.
Suppose you had a method called ReturnArray():
class Class2
{
public string[] ReturnArray()
{
string[] str = new string[] { "hello", "hi" };
return str;
}
}
If you called ReturnArray in your main class like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(class2.ReturnArray());
}
it will return System.String[] because MessageBox.Show(...) takes a string as an argument, in this case.
So you'll also get the same result by using MessageBox.Show(class2.ReturnArray().ToString());
Instead, you may want to do something like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
string[] strArray = class2.ReturnArray();
listBox1.Items.AddRange(strArray);
}

how can we display the elements of an integer type array in C#

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();
}
}

Why is my loop returning the same value from a method that I am calling? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Random number generator only generating one random number
My code below is doing this and I don't know why:
IF my toEmailAddresses array contains 2 e-mail addresses, uniqueID[0] and uniqueID[1] will return the same value generated from the Util.CreateRandomPassword(16) method call.
If I step through the code, then both uniqueID[0] and uniqueID[1] will contain different values like it should. But if I run the code as usual, for some reason, the same value gets assigned to my uniqueID array: uniqueID[0] and uniqueID[1] will contain the same value.
I even put in the string tempRandomPassword = null and then assign that to the value returned from the CreateRandomPassword method, but that does not work either.
What am I doing wrong?
//toEmailAddresses.Count array will have two e-mail addresses in it.
string[] uniqueID = new string[2];
for (int i = 0; i < toEmailAddresses.Count(); i++)
{
string tempRandomPassword = null;
tempRandomPassword = Util.CreateRandomPassword(16);
uniqueID[i] = tempRandomPassword;
}
public static string CreateRandomPassword(int passwordLength)
{
//http://madskristensen.net/post/Generate-random-password-in-C.aspx
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
You're creating a new instance of Random with the default seed on every invocation. If the seed is the same it will produce the same sequence of numbers. Store the instance and use that for all invocations.
Your creating a new Random object each time, and since it uses time as a default seed, your getting the same seed, and thus the same numbers.
Make it a field of the class and only create it once.
This is why it worked when you stepped through it by the way. The extra time allowed the seed to change and return different results.
It is because your method uses
Random rd = new Random();
This local instance of Random will auto-initialize using the clock but when two instances are created too close together (in time) they will use the same seed and produce the same random sequence.
As long as you're not calling this from multiple threads you can use a static field as a simple fix:
private static Random _rd = new Random();
public static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
char[] chars = new char[passwordLength];
// Random rd = new Random();
...
}
Use thread sleep in the loop
private void button3_Click(object sender, EventArgs e)
{
string[] uniqueID = new string[2];
string[] toEmailAddresses = new string[2];
toEmailAddresses[0] = "a#1.com";
toEmailAddresses[1] = "b#1.com";
for (int i = 0; i < toEmailAddresses.Count(); i++)
{
uniqueID[i] = CreateRandomPassword(16);
System.Threading.Thread.Sleep(10);
}
for (int i = 0; i < uniqueID.Count(); i++)
MessageBox.Show(i.ToString() + " : " + uniqueID[i]);
}

Categories