CheckedListBox get selected index - c#

How can I get the value of the selected index in a CheckedListBox. I tried via through an if condition and switch cases, but it is not working as expected.
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (checkedListBox1.GetItemCheckState(0)==CheckState.Checked)
{
richTextBox1.Font = new Font(richTextBox1.Font, FontStyle.Bold);
}
}

i think you can use
checkedListBox1.CheckedIndices
Something like
foreach(int index in checkedListBox1.CheckedIndices)
{
if(index == 1)
{
//do something
}
}

Try this:
if(checkedListBox1.CheckedItems.Count != 0)
{
// If so, loop through all checked items and print results.
string s = "";
for(int x = 0; x <= checkedListBox1.CheckedItems.Count - 1 ; x++)
{
s = s + "Checked Item " + (x+1).ToString() + " = " + checkedListBox1.CheckedItems[x].ToString() + "\n";
}
MessageBox.Show (s);
}

Related

Display only Even numbers in C#, using Windows Forms

I think this is a very easy answer and I understand that you enter something like this get an even number:
if (i % 2 == 0)
But I am just struggling to figure out how to slot it into my current code that I have here...
I have a form like so:
I am double clicking the 'Show Numbers' button
And I want the user to click the show numbers button and it only spits out even numbers, regardless if the box is checked or not.
namespace CHECK_BOXES
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "";
if (checkBox1.Checked)
{
for (int i = 1; i <= 20; i++)
{
textBox1.Text += i.ToString() + "\r\n";
}
}
else
{
for (int i = 20; i >= 1; i--)
{
textBox1.Text += i.ToString() + "\r\n";
}
}
}
}
}
Would appreciate any help.
Thank you
Try with this function:
public bool IsEven(int value)
{
return value % 2 == 0;
}
and then update your for each loop with the following statement:
for (int i = 1; i <= 20; i++)
{
if (IsEven(i))
{
textBox1.Text += i.ToString() + "\r\n";
}
}
Or just easily increment i in for loop with 2.
Just do "double"-steps.
for (int i = 0; i <= 20; i += 2) { // <- pay attention, i will be incremented by 2
textBox1.Text += i.ToString() + "\r\n";
}
could be one line with Linq
textBox1.Text = string.Join("\r\n", Enumerable.Range(0, 20)
.Where((_, index) => index % 2 == 0).Select(x => x));

How to sum datagridview selected cell CORRECTLY

it's working but not correctly
... if selecting from up to down it's sum correct somewhere, but Down to up select doesnt summing
private void SalesGridView_SelectionChanged(object sender, EventArgs e)
{
float sumNumbers = 0;
for (int i = 0; i < SalesGridView.SelectedCells.Count; i++)
{
if (!SalesGridView.SelectedCells.Contains(SalesGridView.Rows[i].Cells["TotalBillColumn"]))
{
float nextNumber = 0;
if (float.TryParse(SalesGridView.SelectedCells[i].FormattedValue.ToString(), out nextNumber))
sumNumbers += nextNumber;
label1.Text = "selected value " + sumNumbers;
label2.Text = "nr selected cells " + SalesGridView.SelectedCells.Count.ToString();
}
else
{
}
}
}
Try the following code:
private void SalesGridView_SelectionChanged(object sender, EventArgs e)
{
float sumNumbers = 0;
for (int i = 0; i < SalesGridView.SelectedCells.Count; i++)
{
var selectedCell = SalesGridView.SelectedCells[i];
if (selectedCell.ColumnIndex == SalesGridView.Columns["TotalBillColumn"].Index)
{
float nextNumber = 0;
if (float.TryParse(selectedCell.FormattedValue.ToString(), out nextNumber))
sumNumbers += nextNumber;
}
}
label1.Text = "selected value " + sumNumbers;
label2.Text = "nr selected cells " + SalesGridView.SelectedCells.Count.ToString();
}
Sorry, for the late explanation, when I wrote that answer didn't have time to elaborate what your actual problem is and only gave you a solution that should work.
Your problem can be located at that line:
if (!SalesGridView.SelectedCells.Contains(SalesGridView.Rows[i].Cells["TotalBillColumn"]))
To be precise the following statment will give you wrong results:
SalesGridView.Rows[i]
You will receive unwanted results, because i doesn't fit your requirement of an index of your Rows, so lets look at what you wrote in your for loop.
for (int i = 0; i < SalesGridView.SelectedCells.Count; i++)
Your for loop tries to enumerate the SelectedCells of your SalesGridView.
So lets assume you select 5 cells, than your for loop with enumerate from 0 to exclusive 5, so i will be 0, 1, 2, 3 or 4.
Now lets check again with the problematic statement I mentioned earlier:
SalesGridView.Rows[i]
Does the SelectedCell with for example i = 0 correspone with Rows[0] no it doesn't have to.
Your SelectedCells could be of any row and your for loop will always enumerate from 0 to SelectedCells.Count but your statementment of SalesGridView.Rows[i] will always try to get the Row with the given index of i.
So, for example:
You select 2 cells in row 6 and 7.
SelectedCells.Count will have 2
You enumerate SelectedCells beginning from 0 to exclusive 2, so i will be 0 or 1
Inside your loop you try to access the row with i, by calling SalesGridView.Rows[i]
as mentioned in point 3. i will only be 0 or 1, but I selected 2 cells of the rows 6 and 7
private void button1_Click(object sender, EventArgs e)
{
double result = 0;
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
result = result + double.Parse(cell.Value.ToString());
}
label2.Text = result.ToString();
}
and with TryParse if you want to go on the safe side:
private void button1_Click(object sender, EventArgs e)
{
double result = 0;
double nextNumber = 0;
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
if (double.TryParse(cell.Value.ToString(), out result))
{
nextNumber += result;
label2.Text = nextNumber.ToString();
}
}
}

How can I solve an index out of range error?

I hava a combo box that contains students from a studentList. When I select a student it should populate a text field of the students name. Whenever a student is selected from the combo box I get the following error
ArgumentOutOfRangeException was unhandled
Index was out of range. Must be non-negative and less than the size of the collection.
I think the problem may be in my loop but I'm having trouble finding out how to fix the error, any help would be appreciated
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i;
for (i = 0; i < Main.studentList.Count; i++)
{
if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
{
break;
}
}
txtName.Text = Main.studentList[i].StudentName; //where the error occurs
}
public void ChangeStudent_Load(object sender, EventArgs e)
{
//loading combobox from studentList
foreach (var student in Main.studentList)
{
comboBox1.Items.Add(student.StudentName + " " + student.StudentId);
}
}
The reason it's throwing an error is after the break, i gets incremented. If i was the last item in the list, it's now out of bounds. If it wasn't, it's now pointing to the next item.
The simple solution would be to move the line that is throwing the error above the break;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i;
for (i = 0; i < Main.studentList.Count; i++)
{
if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
{
txtName.Text = Main.studentList[i].StudentName;
break;
}
}
}
Also, consider using a foreach loop. Here's the exact same logic with a foreach loop. It makes it a bit more readable.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (var student in Main.studentList)
{
if (comboBox1.SelectedItem == student.StudentName + " " + student.StudentId)
{
txtName.Text = student.StudentName;
break;
}
}
}
The error occurs because on the last loop in the for loop i is incremented by 1:
i++
It then evaluates to false in the expression:
i < Main.studentList.Count
So when you get to the line where the error occurs I is equal to Main.studentList.Count and so an index out of range error occurs.
If you want to access the last element of the list you can do:
Main.studentList[Main.studentList.Count - 1].StudentName
Alternatively if you want to evaluate the statement on each loop just move it inside of your for loop:
for (int i = 0; i < Main.studentList.Count; i++)
{
if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
{
txtName.Text = Main.studentList[i].StudentName;
break;
}
}
This also has the advantage of keeping the variable i local to the scope of the loop.
Change your code like that and please try again
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int i;
for (i = 0; i < Main.studentList.Count; i++)
{
if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
{
txtName.Text = Main.studentList[i].StudentName;
break;
}
}
}
You are using the same variable(i) for range calculation and also assignment.
Try this.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int j;
for (int i = 0; i < Main.studentList.Count; i++)
{
if (comboBox1.SelectedItem == Main.studentList[i].StudentName + " " + Main.studentList[i].StudentId)
{
j=i;
break;
}
}
txtName.Text = Main.studentList[j].StudentName; //where the error occurs
}
public void ChangeStudent_Load(object sender, EventArgs e)
{
//loading combobox from studentList
foreach (var student in Main.studentList)
{
comboBox1.Items.Add(student.StudentName + " " + student.StudentId);
}
}

How to output only a part of values from ListBox?

I would like to output only a part of items from listBox1 like:response.response.items[counter].first_name to lable_name.Text. How can I do that?
Part of method:
for (int counter = 0; counter < response.response.items.Count; counter++)
{
listBox1.Items.Add(response.response.items[counter].first_name + " " + response.response.items[counter].last_name + Environment.NewLine);
}
The way I output items to lable:
private void listBox1_DoubleClick(object sender, EventArgs e)
{
int count = listBox1.Items.Count -1;
for (int counter = count; counter >= 0; counter--)
{
if (listBox1.GetSelected(counter))
{
lable_name.Text= listBox1.Items[counter].ToString();
}
}
}
lable_name.Text = listbox1.Items[counter].ToString().Split(' ')[0];
could be one of the options ...
just make sure what charackter are qou spliting on as well as the text in string.

Odd problems with CheckListBoxes in C#

I have quite a few check boxes in an application I'm playing with. So, I decided to use a CheckedListBox instead. I iterate through the list with the code below...
private void CheckedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckedListBox1.CheckedItems.Count != 0)
{
string x = "";
for (int x = 0; x <= ServicesCheckedListBox3.CheckedItems.Count - 1; x++)
{
x = x + "Checked Item " + (x + 1).ToString() + " = " + ServicesCheckedListBox3.CheckedItems[x].ToString() + "\n";
}
Line.Add(x);
}
}
The out put gives me this...
System.Collections.Generic.List`1[System.String].
I'm very new and have never seen this. The application runs fine but the out put doesn't come out right. Any suggestions?
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string x="";
foreach(string chk in checkedListBox1.CheckedItems)
{
x = x + "Checked Item " + checkedListBox1.Items.IndexOf(chk).ToString() + " = " + chk + "\n";
}
MessageBox.Show(x);
}
Use foreach to iterate through CheckedItems
foreach(string item in ServicesCheckedListBox3.CheckedItems)
{
Line.Add(item)
}

Categories