WPF Button click not properly comparing variable to array value - c#

new to WPF so not sure if there is some sort of syntax that I am missing or what.
Course choice;
int totalCredits = 0;
int classesRegistered = 0;
string[] registeredCourses = new string[3];
private void button_Click(object sender, RoutedEventArgs e)
{
if (classesRegistered < 3)
{
choice = (Course)(this.comboBox.SelectedItem);
if ((!choice.Equals(registeredCourses[0]))
&& (!choice.Equals(registeredCourses[1]))
&& (!choice.Equals(registeredCourses[2])))
{
registeredCourses[classesRegistered] = choice.ToString();
this.listBox.Items.Add(registeredCourses[classesRegistered]);
classesRegistered = classesRegistered + 1;
}
}
}
So I don't want the choice to be added to the listbox if its already registered to one of the array's values. What is it I'm missing?

Your if statement is comparing a string to a Course object, you may change it to below:
if(!registeredCourses.Any(obj=> obj.Equals(choice.ToString())))

Related

Fill an array with numbers given by the user adding a number each time he presses the button

I have a basic form with a button and a textbox to insert a number
I want to keep the number inserted in the first index of the array, then if I put another number and I click the button, I want that number to be stored in the second index of the array and so on
I have to make a loop to increment the index but if I use the loop, the first number I put in the box, it's going to be stored in all the indexes of the array
Here's my code (doesn't work)
public partial class EXERCISES_ARRAYS : Form
{
int[] numbers = new int[5];
private void btnAdd_Click(object sender, EventArgs e)
{
int i = 0;
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
for (int j = 0; j < 5; j++)
{
numbers[i] = insertedNumber;
i++;
if (i == 5)
{
btnAdd.Enabled = false;
}
}
}
}
You want a List, rather than an array. That will take care of all of this for you:
public partial class EXERCISES_ARRAYS : Form
{
List<int> numbers = new List<int>();
private void btnAdd_Click(object sender, EventArgs e)
{
numbers.Add(int.Parse(txtInsertedValue.Text));
}
}
I don't think you need to add a for loop for this. Try this
int[] numbers = new int[5];
int i = 0;
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
numbers[i] = insertedNumber;
i++;
if (i == 5)
{
btnAdd.Enabled = false;
}
}

Assigning unique values to the index of an array

I am trying to make my button take input from a textbox and add it to the index. The problem is that with everything I have tried, I cannot get it to give a unique value to each position in the index.
private void addBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < nums.Length; i++)
{
if (nums[0] == 0)
{
nums[0] = int.Parse(inputText.Text);
i++;
}
if (nums[1] == 0)
{
nums[1] = int.Parse(inputText.Text);
i++;
}
}
MessageBox.Show(nums[i].ToString());
}
Right now my code inserts the value to both index positions instead of assigning a value to position 0 and then allowing the user to insert a different value into position 1 and so on and so on.
It's not clear what your intent is, but it looks like you might be trying to add numbers to an array. This code will assign the parsed string to the first item in the array that isn't zero.
private void addBtn_Click(object sender, EventArgs e)
{
int i = 0;
for (; i < nums.Length; i++)
{
if (nums[i] == 0)
{
nums[i] = int.Parse(inputText.Text);
break;
}
}
MessageBox.Show(nums[i].ToString());
}
But this would be a better way, because the user might type "0":
private int _lastUsedIndex = -1;
private void addBtn_Click(object sender, EventArgs e)
{
var number = int.Parse(inputText.Text);
// Increment by one
++_lastUsedIndex;
nums[_lastUsedIndex] = number;
MessageBox.Show(number.ToString());
}
But still, arrays aren't a great idea: They can't grow as you add things. First they're bigger than you need, then suddenly they're too small and you crash. We have better options now. Unless your teacher insists that you must use an array, use List<int> instead. In this version, we'll also use a different way to parse the number, which won't crash if the user types "LOLWUT?!?!" instead of a number:
private List<int> nums = new List<int>();
private void addBtn_Click(object sender, EventArgs e)
{
int number;
if (int.TryParse(inputText.Text, out number))
{
nums.Add(number);
MessageBox.Show(number.ToString());
}
else
{
MessageBox.Show(inputText.Text + " isn't a number, smart guy.");
}
}

How to get correct answer for quiz when randomly assigning answers, from a dataset, to a buttons text attribute

I have a quiz that I'm writing and I'm using 4 buttons text attributes to display the multiple choice answers. 1 is correct, the other 3 are wrong.
The answers are from my dataset and then randomly assigning the answers to the buttons text attributes, when the user selects an answer then it moves along to the next question and doing the same thing, as it should.
But what I can't seem to figure out is, since I'm assigning the answers randomly, how do I keep track of answer that was selected? Here is the code...
Label1.Text = ds.Tables[0].Rows[myNum]["Question"].ToString();
string[] array = new string[4] {
ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString(),
ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString(),
};
// randomize the ordering of the items
System.Random rnd = new System.Random();
array = array.OrderBy(x => rnd.Next()).ToArray();
// each time you run this, the correct answer will be in a different place:
btn1.Text = array[0];
btn2.Text = array[1];
btn3.Text = array[2];
btn4.Text = array[3];
myNum = myNum + 1;
if (myNum == numOfRows)
Response.Redirect("~/Results.aspx");
I have tried this...
ds.Tables[0].Rows[myNum]["CorrectAnswer"].ToString() + "1",
ds.Tables[0].Rows[myNum]["WrongAnswer1"].ToString() + "0",
ds.Tables[0].Rows[myNum]["WrongAnswer2"].ToString() + "0",
ds.Tables[0].Rows[myNum]["WrongAnswer3"].ToString() + "0",
and as expected it didn't work at all, but I tried it any ways.
Any ideas?
Thanks
When you shuffle your array you lose track of the correct solution. This is not what you want. You should always be able to tell from your code which button will be assigned the correct answer. This does not mean you should know which id this button has, but how it gets assigned.
One thing you could do for example is shuffle an array of your button objects, and always assign your correct answer to the first index in that array.
So you create an array of your button objects, shuffle it. You assign the correctAnswerClick handler and the answer string to the first index (0) in that array. You assign the falseClick and wrong answers to index 1, 2 and 3. This way you always know that the correct button has the proper event handler.
The code below is what you want to achieve in Winforms (I don't have ASP installed in VS.Net atm) but it should be easily translated to ASP.Net I think.
button1 to button4 are named btn1 to btn4 in your case.
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
var btnns = new List<Button>();
btnns.Add(button1);
btnns.Add(button2);
btnns.Add(button3);
btnns.Add(button4);
//Shuffle the list
Shuffle<Button>(ref btnns);
//Add an event handler for success to your first button
btnns[0].Click += successClick;
btnns[0].Text = "Correct";
for (int i = 1; i < btnns.Count; i++)
{
btnns[i].Click += failedClick;
btnns[i].Text = "Wrong " + i;
}
}
private void failedClick(object sender, EventArgs e)
{
//Add a true value to the viewstate list
AddAnswer(true);
}
private void successClick(object sender, EventArgs e)
{
//Yay, it's correct
AddAnswer(false);
}
public void AddAnswer(bool correctornot)
{
//I am not 100% sure about the code below (not tested), but it should give you an idea
if (Session["listOfAnswers"] != null)
{
var currentList = (List<bool>) Session["listOfAnswers"];
currentList.Add(correctornot);
Session["listOfAnswers"] = currentlist;
}
else
{
var currentlist = new List<bool>();
currentlist.Add(correctornot);
Session["listOfAnswers"] = currentlist;
}
}
public void Shuffle<T>(ref List<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
Answer taken from here: Randomize a List<T>

Timer and List<string> in C#

I need help with timer and List.
List consist of collection of string say 5 or 6 at a time. Now, I want to display string one on label1 and it should wait for 5s and then display string 2 on label1. I have timer control and I am specifying my code in timer_tick event.
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
int length = myStatus.Length;
for (int i = 0; i < length; i++)
{
string _myStatus = myStatus[i];
//label1.ResetText();
MessageBox.Show("Twitter Status =" + _myStatus);
//label1.Text = _myStatus;
//label1.Visible = true;
}
}
I have specify, Elapse = true and interval = 5000 but still I am not able to display one string at a time. In fact, I am getting last string only. I want to rotate the strings all time.
Can anyone help me.
That's because you're looping through all the strings each time the timer event fires.
Store your index in a private variable and use that instead.
private int _index = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
string _myStatus = myStatus[_index];
//label1.ResetText();
MessageBox.Show("Twitter Status =" + _myStatus);
//label1.Text = _myStatus;
//label1.Visible = true;
if(_index == (myStatus.Length - 1))
_index = 0;
else
_index++;
}
Well it is doing just what you told it to. However, what you told it to do is not what you meant for it to do. Try this.
public class Form1 : Form {
private string[] statuses = { "A", "B", "C", "D", "E" }; // Init with proper values somewhere
private int index = 0;
private void OnTimerTick(object sender, EventArgs e) {
string status = statuses[index];
index++;
if (index == statuses.Length) { // If index = Array.Length means we're
// outside bounds of array
index = 0;
}
}
}
I'd create an int outside of the Tick to hold your position. Make sure you reset it back to 0 when you restart the process.
int MyPosition = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
int length = myStatus.Length;
if((MyPosition + 1) > length)
{
//Index Out of Range
}
else
{
string _myStatus = myStatus[MyPosition];
label1.Text = _myStatus
}
MyPosition++;
}

C# reassigning array values(down one step ex 5-4) that are within an object during a event

Just learning C# (along with object and event programing) and the teacher didn't really show us how to get things done.
class Postion
{
private int[] x_coordinate = new int[100];
private int[] y_coordinate = new int[100];
private double[] speed = new double[100];
private int[] direction = new int[100];
const int MAX_SPEED = 50;
int counter = 0;
public Postion()
{
x_coordinate[counter] = 0;
y_coordinate[counter] = 0;
speed[counter] = 0;
direction[counter] = 0;
}
//get set methods
public int X
{
get
{
return x_coordinate[counter];
}
set
{
x_coordinate[counter] = value;
}
}
There is one more Class between them
The values are frist assigned by a button click.
Airplane newplane = new Airplane();
private void BtnCreate_Click(object sender, EventArgs e)
{
bool box = txtName.Text != "";
if (box == true)
newplane.Name = txtName.Text;
else { }
box = txtx.Text != "";
if (box == true)
newplane.PlanePostion.X = int.Parse(txtx.Text);
else { }
Etc.
I can call on the array values for display for the list box.
private void lsbplanes_SelectedIndexChanged(object sender, EventArgs e)
{
placeholder = newplane.PlanePostion.Counter;
newplane.PlanePostion.Counter = lsbplanes.SelectedIndex;
if (newplane.PlanePostion.Counter < 0)
newplane.PlanePostion.Counter = 0;
else { }
lblxshow.Text = Convert.ToString(newplane.Getx());
but when using a destroy button to remove an item in the list box I need to have it so the box updates with the new values when the user selects the item in the listbox.
This is what I have to try and do it so far, it sets all the ones above to 0s but does remove the the deleted one fine
private void BtnKill_Click(object sender, EventArgs e)
{
if (lsbplanes.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first.", "No item selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
placeholder = lsbplanes.SelectedIndex;
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
while (newplane.PlanePostion.Counter > placeholder)
{
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter--;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
}
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
}
anyone can help me on this?
I was torn in this question, answer exactly what your problem is, or suggest that you redesign it.
#Marc is right you should be using some sort of List<Position> on your Plane object (or a ReadOnlyObservableCollection<Position>).
#Marc is also right, that the problem you are having is that you are trying to push the values down from the end of the list and overwriting them. In these cases it is better to start from the deletion point and pull them down.
So if you have {1,2,3,4,5,6,7,8,9,10} and you delete from item 5, you would have {1,2,3,4,10,10,10,10,10,10}. The code below will let you end up with {1,2,3,4,6,7,8,9,0}
placeholder = lsbplanes.SelectedIndex;
int idx = placeholder;
while (idx < lsbplanes.Items.Count)
{
newplane.PlanePosition.Counter = idx+1;
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter = idx;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
idx++;
}
// Need to zero out elements at the end
newplant.PlanePosition.Counter = lsbplanes.Items.Count;
/* Zeroing code goes here */
newplane.PlanePosition.Counter = placeholder;
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);

Categories

Resources