InvalidArgument=Value '18' is invalid to 'SelectedIndex' Parameter name: SelectedIndex - c#

I have a Button where I am able to save data into the database. To do that I will get the information on Combobox and on a Textbox. I got a collection of items iniside of the Combobox and cannot be changed at the moment.
Right now, I have 17 items and every time I save something it will pull to the next item using cmbID.SelectedIndex += 1;, but every time I pull to the last item from Combobox it will give me an error :
InvalidArgument=Value '18' is invalid to 'SelectedIndex' Parameter name: SelectedIndex
To solve it I've tried to use an if statement:
if (cmbID.SelectedIndex >= 18)
{
cmbID.SelectedIndex = 1;
}
But this is not working, basically if the Combobox reach '18' it should go back to the SelectedIndex choosen by me.
Do you guys have any idea I can solve this problem?

You can't have index more than (item count -1) for the combobox, so
if(cmbID.SelectedIndex == (cmbID.Items.Count - 1))
{
cmbID.SelectedIndex =1;
}else
{
cmbID.SelectedIndex += 1;
}

Related

C# Find the Selected State of all items in a ListBox

I have found many examples on how to find the selected items in a listbox and how to iterate through a listbox;
for(int index=0;index < listBox1.Items.Count; index++)
{
MessageBox.Show(listBox1.Items[index].ToString();
}
or
foreach (DataRowView item in listBox1.Items)
{
MessageBox.Show(item.Row["ID"].ToString() + " | " + item.Row["bus"].ToString());
}
While these methods work great for the selected items, what I have yet to figure out, or find, is how to get the selected state, selected and unselected, of every item in a listbox, as the above only gives the selected.
Basically, I need something like this;
for(int index=0;index < listBox1.Items.Count; index++)
{
if (index.SelectedMode == SelectedMode.Selected)
{
MessageBox.Show(listBox1.Items[index].ToString() +"= Selected";
}
else
{
MessageBox.Show(listBox1.Items[index].ToString() +"= Unselected";
}
}
I've found a snippet that said to use (listBox1.SelectedIndex = -1) to determine the selected state however I've not figured out or found how to build a loop around this to check each item in the listbox.
I've also read that I should put the listbox items into an array, but again nothing about getting the selected state of each item in the listbox.
I know I'll have to iterate through the listbox to accomplish what I'm needing, pretty sure it'll be one of the above loops, however I have yet to find how to extract the selected state of each item in the listbox.
I'm using VS2013, C# Windows Form, .NET Framework 4.0
Thanks in advance for any advice/direction.
This will get you the unselected items:
List<string> unselected = listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>());
You can loop over that list like this:
foreach(string str in listBox1.Items.Cast<string>().Except(listBox1.SelectedItems.Cast<string>()))
{
System.Diagnostics.Debug.WriteLine($"{str} = Not selected");
}
I've made the assumption that you're using string as your item type. If you want to use something else then just replace string with your type and it should still work.
You then loop over the unselected items to do whatever you want with them then loop over listBox1.SelectedItems to do whatever you want with the selected ones.
You can use GetSelected method of the ListBox. It returns a value indicating whether the specified item is selected.
For example, the following code, sets the value of selected to true if the item at index 0 (the first item) is selected:
var selected = listBox1.GetSelected(0);
Example
Te following loop, shows a message box for each item, showing the item text and item selection status:
for (int i = 0; i < listBox1.Items.Count; i++)
{
var text = listBox1.GetItemText(listBox1.Items[i]);
var selected = listBox1.GetSelected(i);
MessageBox.Show(string.Format("{0}:{1}", text, selected ? "Selected" : "Not Selected"));
}

Check if index of List<List<string>> is not null

I have a List<List<string>>, and a ComboBox with 10 items and when the selected index is changed, I use the comboBox_selectedIndexChanged event to bind the data for this index into a ListBox.
I also have Add and Remove buttons that can insert data to my List<List<string>.
How can I prevent the user from selecting index 5 from the ComboBox and add data for it, if the first four are still empty? E.g. tell him that he has to put data in indexes 1, 2, 3 and 4 first.
The click event for the Add button looks like this:
int selectedIndex = comboBox1.SelectedIndex;
//This throws an exception when the selected index is zero,
//of course it makes sense because we can't check if index 0-1 in myList is null
if (myList.Count >= selectedIndex && myList[selectedIndex - 1] != null)
{
myList[selectedIndex].Add(textEdit1.Text);
}
else
MessageBox.Show("Please fill the previous indexes first.");
I know that I can do it in the SelectedIndexChanged event of the ComboBox, but I prefer to do it here.
What about:
int selectedIndex = comboBox1.SelectedIndex;
if (selectedIndex == 1 || (myList.Count >= selectedIndex && myList[selectedIndex - 1] != null))
{
myList[selectedIndex].Add(textEdit1.Text);
}
else
MessageBox.Show("Please fill the previous indexes first.");
if selectedIndex == 1 is true then it wont test the second parameter in the if statement, and won't throw an error. If it is not 1 it will test the second parameter and your error will not be thrown.

Force index selection on combobox when item match C#

I have to force my combobox to change the selected index when user enters text and there is an item match. Right now i am getting the item match from my combobox like this:
List<DataRowView> deliveryRoutes = ((ComboBox)sender).Items.Cast<DataRowView>().ToList();
if (deliveryRoutes.Where(q => q.Row[0].ToString().ToLower().Equals(((ComboBox)sender).Text.ToLower())).Count() != 0)
{
}
This code checks if the user input is a match with the combobox datasource. in my if statement i want to set the selected index of my combobox to be the matched text. Like so:
DeliveryRouteID.SelectedIndex = matchedTextIndex
I have tried getting the index from this without any luck:
deliveryRoutes.Where(q => q.Row[0].ToString().ToLower().Equals(((ComboBox)sender).Text.ToLower())).FirstOrDefault().Row[0]
How would i get the index and set it to be the selected index ?
You're looking for ComboBox.FindStringExact or ComboBox.FindString
cmb.SelectedIndex = cmb.FindStringExact(item);

Searching DataGrid for matching values

I Have a data grid which can be queried based on a comboBox choice .
My code (shown below) is meant to search through the datagrid and if it finds a row with a matching piece of text it is meant to move the datagrids selected index to the corresponding row.
for (int i = 0; i <= DashBoard_DataGrid.Columns.Count - 1; i++)
{
if (DashBoard_DataGrid.Rows[0].ToString().ToLower().Contains(comboBox9.Text.ToString().ToLower()))
{
value = dr.Cells[i].Value.ToString();
// return dr.Cells[i].RowIndex;
DashBoard_DataGrid.SelectedCells[i].RowIndex = dr.Cells[i].RowIndex;
}
}
However I am getting the following error
Error 7 Property or indexer 'System.Windows.Forms.DataGridViewCell.RowIndex' cannot be assigned to -- it is read only
Does anyone know how to fix this error ? searching online hasn't givin a solution
You are trying to change a SelectedCell's row index, which is read-only. If you are trying to change the selected row, you need to set the SelectedIndex for the DataGrid.
DashBoard_DataGrid.SelectedIndex = dr.Cells[i].RowIndex;
Also, try changing SelectedCells to SelectedRows.
try this
.
DashBoard_DataGrid.ClearSelection();
DashBoard_DataGrid.Rows[3].Selected = true;
or if you want to select a specific cell, then
DashBoard_DataGrid.ClearSelection();
DashBoard_DataGrid[0, i].Selected = true;
this will select the first column of the desired row..

Combo Box Size Issue After All Items Are Removed

My application contains a ComboBox that the user can delete items from. When the program starts up it populates the ComboBox from a list of strings read in from a configuration file.
Here is the code to add items:
// version list is an array of strings
foreach (string version in versionList)
{
versionComboBox.Items.Add(version);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after it's been populated:
If the user clicks the Delete button the program removes the selected item from the ComboBox using the following code:
if (versionComboBox.SelectedIndex >= 0)
{
versionComboBox.Items.Remove(versionComboBox.SelectedItem);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after a few items have been removed:
The problem I am having is when the last item is removed the ComboBox resizes itself to the size it was when it was initially populated. There aren't any items in the ComboBox but it sizes itself as if there were.
Here is a screenshot after all the items have been removed:
As you can see the size is too big. I would think that after all the items were cleared it would look like the following:
Any ideas as to why this is happening?
Try to use this at the end of your code when you are filling the combobox items:
comboBoxNumTreno.IntegralHeight = true; // auto fit dropdown list
Then to clear it up:
comboBoxNumTreno.ResetText();
comboBoxNumTreno.Items.Clear();
comboBoxNumTreno.SelectedIndex = -1;
comboBoxNumTreno.DropDownHeight = 106; // default value
comboBoxNumTreno.IntegralHeight = false;
I know this is an old post, but it took me a long time to figure this out and I wanted to let anyone in the future know. After you clear your combo box just do a blank add items and it resets the height.
comboBox1.Items.Clear();
comboBox1.Items.Add("");
To clear your combo box you can add this:
if (versionComboBox.Items.Count == 0)
{
versionComboBox.Text = string.Empty;
versionComboBox.Items.Clear();
versionComboBox.SelectedIndex = -1;
}
Another approach is to manipulate the items in the data source and rebind the control each time (a lot less for you to worry about).
set DropDownHeight property to fix size
versionComboBox.DropDownHeight = 106; // default value

Categories