Circular show with previous and next buttons - c#

Say I have a list: 1 5 6 10
When I click on next and the List item showed is already 10.. I want to bring the user back to 1 and same in the other way when I click previous and the List item showed is already 1.. I want to bring the user back to 10.. Here is what I tried but I always get that the "i (contor) can't be negative or greater than List.Count" :
public int i = 0;
private void nextbutton_Click(object sender, EventArgs e)
{
++i;
if (sweaterclicked)
{
if(SweatersList.Count != 1)
if (i >= SweatersList.Count - 1)
{
i = 0;
pictureBox1.Image = SweatersList[i];
}
else pictureBox1.Image = SweatersList[i];
}
}
private void previousbutton_Click(object sender, EventArgs e)
{
--i;
if (sweaterclicked)
{
if (SweatersList.Count != 1)
{
if (i < 0)
{
i = SweatersList.Count;
pictureBox1.Image = SweatersList[i];
}
else pictureBox1.Image = SweatersList[i];
}
}
}

Array or list indexes in C# start at zero, so the largest in-range index is one less than the count of items in the collection. Therefore, SweatersList.Count, hence i, is out of range here:
i = SweatersList.Count;
pictureBox1.Image = SweatersList[i];
So when you want to start over at the last valid index, you need to subtract one from SweatersList.Count:
i = SweatersList.Count - 1;
I don't know why you're incrementing and decrementing outside the if (sweaterclicked) blocks, but I presume you do.

Related

How to check range in checkedlistbox c# winforms?

I have a checkeboxlist with 100 items. Obviously user can check items one by one as many as he need, but I would like to give to user option check range of items (let's say with Shift hold button). So, user check one of the items (let's say item index 5) and then press and hold shift button and check next item (index 10), so I range of the items should be checked from 5...10
I have not found anything about such implementation, looks like it doesn't exist and no one did such kind of things.
How to do it?
Keep track of your last index:
int lastIndex = -1;
In your form's constructor, wire things up:
public Form1() {
InitializeComponent();
checkedListBox1.CheckOnClick = true;
checkedListBox1.SelectedIndexChanged += CheckedListBox1_SelectedIndexChanged;
checkedListBox1.MouseDown += CheckedListBox1_MouseDown;
}
And then use these methods to change the items in the range:
private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e) {
lastIndex = checkedListBox1.SelectedIndex;
}
private void CheckedListBox1_MouseDown(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left && Control.ModifierKeys == Keys.Shift) {
var useIndex = Math.Max(lastIndex, 0);
var x = checkedListBox1.IndexFromPoint(e.Location);
if (x > -1 && x != useIndex) {
if (useIndex > x) {
for (int i = useIndex - 1; i > x; i--) {
checkedListBox1.SetItemChecked(i, !checkedListBox1.GetItemChecked(i));
}
} else {
for (int i = useIndex + 1; i < x; i++) {
checkedListBox1.SetItemChecked(i, !checkedListBox1.GetItemChecked(i));
}
}
}
}
}

How to make text selection increment on textbox

I need to finish a program on visual studio with forms, I have a textbox(txtUser), another textbox(txtKerko) and a button(btnKerko). So the program goes like this, the user write some text on txtUser and write any word or text on txtKerko and when btnKerko is clicked that word written on txtKerko should be selected on txtUser, if there are more than one of that word all the words should be selected on every btnKerko click. It's almost ready but I couldn't do the part when there are more than one word to increment one by one. This is the event code for btnKerko :
private void BtnKerko_Click(object sender, EventArgs e)
{
if (txtUser.Text.Contains(txtKerko.Text) == true)
{
txtUser.Focus();
string teksti = txtUser.Text;
txtUser.SelectionStart = teksti.IndexOf(txtKerko.Text);
txtUser.SelectionLength = txtKerko.TextLength;
}
else
{
MessageBox.Show("Nuk u gjet");
}
}
Yes, you can do it if you want to select the word one by one. You can use this code :
int lastIndex = 0;
private void BtnKerko_Click(object sender, EventArgs e)
{
txtUser.Focus();
int index = txtUser.Text.IndexOf(txtKerko.Text, lastIndex);
if (index != -1)
{
lastIndex = index + 1;
txtUser.SelectionStart = index;
txtUser.SelectionLength = txtKerko.TextLength;
}
}
As you can see, the variable lastIndex is holding the last selection in each click of the button. I guess you know that the second parameter of IndexOf method tells to start finding the index from that second parameter value.

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 array data from one Click Method to another one

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

Global array not being accessed correctly

Below is my current code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public int[] trialArray = new int[10];
public int trialCounter = -1;
private void button1_Click(object sender, EventArgs e)
{
bool button1Click = true;
if (button1Click == true)
{
ITIpanel.Visible = true;
for (int i = 0; i < trialArray.Length; i++) { trialArray[i] = -1; } // Set default value through array
int counter = 0;
Random rnd = new Random();
while (counter < 10 / 2)
{ // Red trials, fill half array
int index = rnd.Next(0, 10 - 1);
if (trialArray[index] == -1) { trialArray[index] = 1; ++counter; } //if unchanged value, change it
}
while (counter < 10)
{
int index = rnd.Next(0, 10);
if (trialArray[index] == -1) { trialArray[index] = 2; ++counter; }
}
}
}
private void ITIpanel_Paint(object sender, PaintEventArgs e)
{
if (ITIpanel.Visible == true)
{
trialCounter += 1;
timer1.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
ITIpanel.Visible = false;
timer1.Enabled = false;
if (trialArray[trialCounter] == 1) { redstimPanel.Visible = true; }
else { bluestimPanel.Visible = true;}
if (trialCounter == 9) { Application.Exit(); }
}
public int counter = 0;
public event EventHandler Clicked5TimesEvent;
private void OnClicked5TimesEvent()
{ if (Clicked5TimesEvent != null) { Clicked5TimesEvent(this, EventArgs.Empty); } }
private void bluestimPanel_MouseDown(object sender, EventArgs e)
{
//FR requirement
counter++; if (counter % 5 == 0) { redstimPanel.Visible = false; ITIpanel.Visible = true; }
}
private void redstimPanel_MouseDown(object sender, EventArgs e)
{
//FR requirement
counter++; if (counter % 5 == 0) { redstimPanel.Visible = false; ITIpanel.Visible = true; }
}
}
}
As you can see, I am attempting to make a global array with 10 items. On the button click the 10 items are supposed to be altered such that half contain the value 1 and the other half contain the value 2.
Then, on the timer tick, depending on the value in the trialCounter, which determines the part of the array to be accessed, it should display either the redstimPanel or the bluestimPanel.
Therefore, if the 'trialCounter' is equal to 8, and 8 in the TrialArray is equal 1, the 'redstimPanel' should become Visible. Alternatively, if 8 in the 'TrialArray' is equal to 2, the 'bluestimPanel' should become Visible.
This, however, is not working as I would like it to. Thus, there are clearly some issues with my code. Do you all have any suggestions?
You never reset counter, or have the second loop (the one setting the 2s) be the full array.
There is also an error with the random number, rnd.Next(a,b) a - lower bound (inclusive), b - upper bound (exclusive). So it should be rnd.Next(0,10); so you have a chance of populating the last array position.
while (counter < 10 / 2) { // Red trials, fill half array
int index = rnd.Next(0, 10);
if (trialArray[index] == -1) { trialArray[index] = 1; ++counter; } //if unchanged value, change it
}
//Counter on the first loop here is already 5 (it exited the previous loop)
//So allow it to get to 10, and populate the FULL array.
while (counter < 10) {
int index = rnd.Next(0, 10);
if (trialArray[index] == -1) { trialArray[index] = 2; ++counter; }
}
Allow me to give you some tips and some explanations regarding your code:
First of all, you probably wanted that local button1Click variable to know later on whether the button has been clicked or not. For that to work, you should place it outside that function, otherwise it's never going to be used, and will be true with every button click, something like this:
bool button1Click = false;
private void button1_Click(object sender, EventArgs e)
{
if (!button1Click)
{
When you have a condition, you want the code to decide, whether an expression is true or false you may omit the part "== true" because it doesn't add anything new.
You have two whiles. Your idea was to run the counter until 5, with the first piece of code, and then from 5 to 10 the second piece of code. Now let me try to explain what is actually going on. The counter will go on until 5 filling 1s at random indices. Then at 5, the expression in the while will become false and it breaks out from the loop. Since the second while has the very same expression, it simply avoids it and goes on. One of the many solutions would be to have an if in the loop like this:
while (counter < 10)
{
if (counter<5)
{
// fill red
}
else
{
// fill blue
}
}
The way you fill up the values in your array. Have you thought about what's going to happen when the same index will be generated several times? It means it'll overwrite the previous value while certain index will remain -1.

Categories

Resources