I have a CheckBoxList with a SelectedIndexChanged event, where I add the Value of the selected ListItem to a variable. I want to substract the Value when the item is unchecked.
I tried SelectedIndex but returns -1 and SelectedItem returns null. And the EventArgs argument doesn't have any data to help...
You should use the Items property. In other words, your variable should start with its value set to whatever it should be before applying the selected items. Then, iterate over the items, applying your logic against the variable one item at a time for each item that is selected. Then, no matter what the user selects or de-selects, you'll always arrive at the proper value for your variable.
int myValue = 0;
foreach(ListItem item in cbl.Items)
{
if(item.Selected) myValue += int.Parse(item.Value);
}
Related
I have a small project where I get some values from a txt and put inside of a ListView. I need to get the selected value when I click in some item, the first item that I ever select, works fine, but if I try to select again, I get an exception.
This is what I did..
Json = new StreamReader(openDialog.FileName).ReadToEnd();
var ParsedValue = JsonValue.Parse(Json);
Parsed = JsonConvert.DeserializeObject<List<Model>>(ParsedValue.ToString());
foreach (var item in Parsed)
{
var rows = new string[] { item.car, Convert.ToString(item.age )};
var items = new ListViewItem(rows)
{
Tag = item
};
ListViewCars.Items.Add(items);
}
The List view is Filled.
And to get the Item selected from the list :
private void cartsList_SelectedIndexChanged(object sender, EventArgs e)
{
ItemSelected = (Model)ListViewCars.SelectedItems[0].Tag;
}
I can only get the value that I select first when the program runs.
The exception :
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index'
Check out the documentation on ListView.SelectedIndexChanged. Specifically, look at the Remarks section, which reads:
The SelectedIndices collection changes whenever the Selected property of a ListViewItem changes. The property change can occur programmatically or when the user selects an item or clears the selection of an item. When the user selects an item without pressing CTRL to perform a multiple selection, the control first clears the previous selection. In this case, this event occurs one time for each item that was previously selected and one time for the newly selected item.
I added the emphasis. This means that when you select the second item, the currently selected item is unselected and SelectedIndexChanged is triggered before the new item is selected. So when you try to get the first selected item with ListViewCars.SelectedItems[0].Tag you get that ArgumentOutOfRangeException because there are no selected items.
You need to add a check to the top of your event handler to make sure that there is at least one selected item before accessing SelectedItems[0].
For example if I click on the first item it will be at index 0.
If I click on item 15 then the index should be 16.
I tried
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = listView1
}
But I'm not sure if this is the right event or I should use the listView1_Click event ?
And the listView1 does not have any property SelectedIndex.
And last thing is I want to get the item text according to the index of the item I clicked on.
Assuming you want the index of the currently selected item you can do it like this :
int index = ListView1.FocusedItem.Index
Use ListView.SelectedIndices property:
List<int> selectedIndices = listView1.SelectedIndices.Cast<int>().ToList();
It returns collection of selected indices (because by default you can select several items in listview if you click on items with Ctrl or Shift key pressed). Also note that when you deselect all items, this collection will be empty and things like listView1.SelectedIndices[0] will throw IndexOutOfRange exception.
But if you will set MultiSelect property to false. Then this collection will always contain zero or one item. You can use Count property of SelectedIndicesCollection to check if item was selected:
if (listView1.SelectedIndices.Count > 0)
{
int selectedIndex = listView1.SelectedIndices[0];
}
You need to use the selected indices list you can also do this be item too.
listView1.SelectedIndices[0]
First you can get listview item object like below
ListViewItem lst=(ListViewItem)listView.SelectedItems[0];
from that object(lst) you can get the text like below
string text=lst.Content.ToString();
According to MSDN, there is still SelectedIndex. In my opinion your event is wrong, but you can still see it by .SelectedIndex. As it was mentioned before.
UPDATE: according to the comment, the link is fixed for the correct case.
Hi I am using the following code in the form load
Combobox1.DataSource=GetItems();
Then by default first item is selected.
I suppose your ComboBox has the DropDownStyle property set to DropDownList. When it is, setting the Datasource automatically sets the SelectedIndex to 0 (first element in the list). You could write:
Combobox1.DataSource=GetItems();
Combobox1.SelectedIndex = -1;
You're not appending data, you're replacing it entirely. So the SelectedIndex will be reset. You could remember it and then set it back like so
int oldIndex = Combobox1.SelectedIndex;
Combobox1.DataSource= GetItems();
Combobox1.SelectedIndex = oldIndex; //should check to see if the new list is long enough.
I have few items on my ComboBox items collection, and i'd like to select one item from this list and set it as default item - when app starts - this item is already on comboBox.
I'm trying something like that:
SelectPrint11.SelectedIndex=2;
but error is:
System.ArgumentOutOfRangeException: InvalidArgument=Value of '2' is not valid for 'SelectedIndex'
Edit:
In mylist are 3 items, Printer1, Printer2, Printer3. All are added in ComboBox Properties -> Items -> Collection
You can set using SelectedIndex
comboBox1.SelectedIndex= 1;
OR
SelectedItem
comboBox1.SelectedItem = "your value"; //
The latter won't throw an exception if the value is not available in the combobox
EDIT
If the value to be selected is not specific then you would be better off with this
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
Remember that collections in C# are zero-based (in other words, the first item in a collection is at position zero). If you have two items in your list, and you want to select the last item, use SelectedIndex = 1.
private void comboBox_Loaded(object sender, RoutedEventArgs e)
{
Combobox.selectedIndex= your index;
}
OR if you want to display some value after comparing into combobox
foreach (var item in comboBox.Items)
{
if (item.ToString().ToLower().Equals("your item in lower"))
{
comboBox.SelectedValue = item;
}
}
I hope it will help, it works for me.
this is the correct form:
comboBox1.Text = comboBox1.Items[0].ToString();
U r welcome
This means that your selectedindex is out of the range of the array of items in the combobox. The array of items in your combo box is zero-based, so if you have 2 items, it's item 0 and item 1.
first, go to the form load where your comboBox is located,
then try this code
comboBox1.SelectedValue = 0; //shows the 1st item in your collection
ComboBox1.Text = ComboBox1.Items(0).ToString
This code is show you Combobox1 first item in Vb.net
I have a drop down list control populated with items and some code to take the currently selected item value. The problem is I only get the value of the first item in the list regardless of what item is actually selected.
Here is my code to populate the drop down:
protected void displayCreateCategories()
{
StoreDataContext db = new StoreDataContext();
var a = from c in db.Categories
orderby c.Name
select new{catName= c.Name,
catId=c.CategoryID};
ddlCategory.DataSource = a;
ddlCategory.DataTextField = "catName";
ddlCategory.DataValueField = "catId";
ddlCategory.DataBind();
}
To get the value of the currently selected item which in my case is always of type integer I do label1.text=Convert.toInt32(ddlCategory.SelectedValue);
I get the selected value, but it is always for the 1st item in the list. I'm pulling my hair out over this. :(
I suspect you're running the list loading code every time the page loads, which is destroying the list, repopulating the list, and auto-selecting the first item before your selection retrieval code gets run.
Use this construction in Page_Load:
if (!IsPostBack)
{
// Initial control population goes here
}
Data binding will reset the control's selected value so make sure you retrieve the selected value before data binding on postback.