Select next item in ListView - c#

I have a method that removes currently selected item in a ListView
listView1.Items.Remove(listView1.SelectedItems[0]);
How do I select the next in the ListView after removing the selected one?
I tried something like
var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
listView1.SelectedItems[0].Index = index;
But I get the error
Property or indexer 'System.Windows.Forms.ListViewItem.Index' cannot be
assigned to -- it is read only
Thank you.

I had to add one more line of code to a previous answer above, plus a check to verify the count was not exceeded:
int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
// Prevents exception on the last element:
if (selectedIndex < listview.Items.Count)
{
listview.Items[selectedIndex].Selected = true;
listview.Items[selectedIndex].Focused = true;
}

ListView doesn't have a SelectedIndex property. It has a SelectedIndices property.
Gets the indexes of the selected items in the control.
ListView.SelectedIndexCollection indexes = this.ListView1.SelectedIndices;
foreach ( int i in indexes )
{
//
}

try use listView1.SelectedIndices property

If you delete an item, the index of the "next" item is the same index as the one you just deleted. So, I would make sure you have listview1.IsSynchroniseDwithCurrentItemTrue = true and then
var index = listView1.SelectedItems[0].Index;
listView1.Items.Remove(listView1.SelectedItems[0]);
CollectionViewSource.GetDefaultView(listview).MoveCurrentTo(index);

I've done this in the following manner:
int selectedIndex = listview.SelectedIndices[0];
selectedIndex++;
listview.Items[selectedIndex].Selected = true;

I actually had to do this:
int[] indicies = new int[listViewCat.SelectedIndices.Count];
listViewCat.SelectedIndices.CopyTo(indicies, 0);
foreach(ListViewItem item in listViewCat.SelectedItems){
listViewCat.Items.Remove(item);
G.Categories.Remove(item.Text);
}
int k = 0;
foreach(int i in indicies)
listViewCat.Items[i+(k--)].Selected = true;
listViewCat.Select();
to get it to work, none of the other solutions was working for me.
Hopefully, a more experienced programmer can give a better solution.

Related

How can I set selected in a ComboBox, based on ValueMember?

I have a combobox with the following structure. Also, I am getting a fld_id from another source and based on that id I need to select the corresponding item in the ComboBox. How can I do that?
comboBoxCustomers.DataSource = customers;
comboBoxCustomers.ValueMember = "fld_id";
comboBoxCustomers.DisplayMember = "fld_name";
Example:
List could contain these items
fld_id fld_name
65 Item1
68 Item2
69 Item3
I need to set Item 68 as selected.
Use Following:
comboBoxCustomers.SelectedValue = fld_id(which you are getitng from another source)
I don't have enough reputation to post a comment. This:
comboBoxCustomers.SelectedValue = fld_id
works great :) But AFTER showing the form, otherwise it will fail.
if you use datasource of the combobox, you can cast the datasource back to the list, find the item and use that item to set the selected item:
var stores = cbxStores.DataSource as List<store>;
var store = stores.Where(w => w.store_code == _station.store_code).FirstOrDefault();
cbxStores.SelectedItem = store;
Simplest procdure I found for myself:
You can bind it into some function with perameters while funtion is called.
Hope it is going to help you guys:
int Idd = Convert.ToInt32(your value for the combobox you want to be selected);
for (int i = 0; i < myComboBox.Items.Count; i++)
{
myComboBox.SelectedIndex = i;
if (Convert.ToInt32( myComboBox.SelectedValue ) == Idd )
{break;}
}

how to get the selected values of Listbox in c#

i had bind the listbox where datasource of listbox is list.how can i get the selected value of selected list item in listbox.my sample code as follows
pdfList = attendanceDetailsPresenter.GetPredefinedDetails();
this.lstCompanies.DataSource = pdfList;
this.lstCompanies.DisplayMember = "CompanyName";
this.lstCompanies.ValueMember = "CompID";
this.lstDepartments.BindingContext = new BindingContext();
this.lstDepartments.DataSource = pdfList;
this.lstDepartments.DisplayMember = "DepartmentName";
this.lstDepartments.ValueMember = "DeptID";
if (lstCompanies.SelectedItems.Count < 0)
{
MessageBox.Show("Please Select Any one Company");
return attendanceCalculationDetailsDataList;
}
else
{
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
}
can anyone solve my problem please.
First of all, the Count of a list can never be less than zero. It's always >= 0.
Then, when you data-bind your list, the items usually are of type DataRowView (which you should be able to verify by debugging your application). If that is right, you should have to cast each selected item to DataRowView and then cast the value of its Row property to the type you expect.
I just noticed that in the following loop you're not even using the selected items, but always the SelectedValue:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(int.Parse(lstCompanies.SelectedValue.ToString()));
}
Try changing this to:
for (int i = 0; i < lstCompanies.SelectedItems.Count; i++ )
{
attendanceCalculationDetailsData.CompanyID.Add(((<WhatEverClassYouUse>)lstCompanies.SelectedItems[i]).CompanyID);
}
Explanation: If more than one item in the list are selected, the items are added to the SelectedItems collection. You can iterate these items. Each item will be an object of DataRowView (when data bound to a DataTable or DataView) or a class in a collection.
As you didn't tell us the type of objects returned by GetPredefinedDetails, I substituted it with WhatEverClassYouUse. Cast this to the right type.

How to set Selected item of ComboBox in C# Windows Forms?

I am trying to set selected item of comboBox on click event of DataGrid, but I could not. I have googled and tried different ways but without success.
For me SelectedIndex is working, but I could not find the index of items in ComboBox, so I could not select the item.
Not working code:
for (int i = 0; i < cmbVendor.Items.Count; i++)
if (cmbVendor.Items[i].ToString() == Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor")))
{
cmbVendor.SelectedIndex = i;
break;
}
You can get your item index by the .Items.IndexOf() method. Try this:
comboBox1.SelectedIndex = comboBox1.Items.IndexOf(gridView1.GetFocusedRowCellValue("vVendor"));
You don't need to iterate.
You can find more information in Stack Overflow question How do I set the selected item in a comboBox to match my string using C#?.
The following is working for me perfectly. Pass any value or Text which is available in the combobox.
comboBox1.SelectedIndex = comboBox1.FindString(<combobox value OR Text in string formate>);
You have it in your if:
cmbVendor.SelectedItem = cmbVendor.Items[i];
At last I found it out. It's:
cmbVendor.Text = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
The SelectedText property is for the selected portion of the editable text in the textbox part of the combo box.
If you have set ValueMember property for the ComboBox control, you can simply assingn the Value to the ComboBox control's SelectedValue property. You don't have to find the index explicitly.
Here's an example:
public class Vendor{
public int VendorId {get; set;}
public string VendorName {get; set;}
}
// Inside your function
var comboboxData = new List<Vendor>(){
new Vendor(){ vendorId = 1, vendorName = "Vendor1" },
new Vendor(){ vendorId = 2, vendorName = "Vendor2" }
}
cmbVendor.DataSource = comboboxData;
cmbVendor.DisplayMember = "VendorName";
cmbVendor.ValueMember = "ValueId";
// Now, to change your selected index to the ComboBox item with ValueId of 2, you can simply do:
cmbVendor.SelectedValue = 2;
Assuming gridView1.GetFocusedRowCellValue("vVendor") really works as expected, the following code should fix the problem.
string selected = Convert.ToString(gridView1.GetFocusedRowCellValue("vVendor"));
foreach ( var item in cmbVendor.Items )
{
if (string.Compare(item.ToString(), selected, StringComparison.OrdinalIgnoreCase) == 0)
{
cmbVendor.SelectedItem = item;
break;
}
}
The original code had multiple calls to gridView1.GetFocusedRowCellValue("vVendor"), whereas you only need one.
The suggested "comboBox1.Items.IndexOf(" assumes too much about the content of cmbVendor.Items.
I had a similar problem and worked it out partially with the help of the other answers here. First, my particular problem was that
combobox1.SelectedItem = myItem;
was not working as expected. The root cause was that myItem was an object from a group which was effectively the same list as the items in the combobox, but it was actually a copy of those items. So myItem was identical to a valid entry, but itself was not a valid object from the combobox1 container.
The solution was to use SelectedIndex instead of SelectedItem, like this:
combobox1.SelectedIndex = get_combobox_index(myItem);
where
private int get_combobox_index(ItemClass myItem)
{
int i = 0;
var lst = combobox1.Items.Cast<ItemClass >();
foreach (var s in lst)
{
if (s.Id == myItem.Id)
return i;
i++;
}
return 0;
}
ComboBox1.SelectedIndex= ComboBox1.FindString("Matching String From DataGrid Cell value")
Try this this will work fine in C# Windows application
this works for me.....
string displayMember = ComboBox.DataSource.To<DataTable>().Select("valueMemberColumn = '" + value + "'")[0]["displayMember"].ToString();
ComboBox.FindItemExact(displayMember, true).Selected = true;

WPF DataGrid Remove SelectedItems

Recently I've been working on a project which imports data programmicaly into a WPF DataGrid.
I'm almost done with the project but the thing that I left out was a button to remove selected cells and this is where I'm stuck!
I wrote this code using my basic knowledge of DataGrids:
var grid = dataGrid1;
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
grid.Items.Remove(grid.SelectedItems[i]);
};
}
Works fine on removing only the item selected just like CurrentItem but it doesn't remove anymore than 2 selected items!
The DataGrid I have should at least contain a minimum of 100 items. I've added a remove all option but this is also necessary.
I'll be thankful if anyone gives me the solution.
By removing selected item you are changing SelectedItems collection. You should copy it first and then start removing.
This also worked well for me.
while (dataGrid1.SelectedItems.Count > 0){
dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}
The mistake you are doing here you are removing items during loop whaich is messing with loop count so make a copy grid and remove selecteditem from it and then equlize it by the orignal one..
Check this out
var grid = dataGrid1;
var mygrid = dataGrid1
if (grid.SelectedIndex >= 0)
{
for (int i = 0; i <= grid.SelectedItems.Count; i++)
{
mygrid .Items.Remove(grid.SelectedItems[i]);
};
}
grid = mygrid;
This worked for me...
while (dataGrid1.SelectedItems.Count > 0){
dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}
This worked for me...
if (DataGrid1.SelectedItem != null)
{
((DataRowView)(DataGrid1.SelectedItem)).Row.Delete();
}
A while loop using the SelectedItem instead of the SelectedIndex
while (dataGrid1.SelectedItems.Count > 0){
if (dataGrid1.SelectedItem == CollectionView.NewItemPlaceholder)
dataGrid1.SelectedItems.Remove(grid.SelectedItem);
else
dataGrid1.Items.Remove(dataGrid1.SelectedItem);
}
I have stack with the same problem as an author. And found quite beautiful (I think) solution.
And so the main problem is that the SelectedItems dynamic, and when you delete one row, it is recalculated again.
And so my code looks like this:
for (int i = -datagrid1.SelectedItems.Count; i < datagrid1.SelectedItems.Count; i++)
{
datagrid1.SelectedItems.RemoveAt(datagrid1.SelectedIndex);
}
So, every time the for loop is doing step 1, datagrid1.SelectedItems.Count is decreased by 1, and the variable i increases.
Do While dgData.SelectedItems.Count > 0
dgData.SelectedItem.Row.Delete()
Loop
My solution (if you are using adonet with autogeneratecolumns=true);
for (int i = dgv.SelectedItems.Count-1; i >= 0; i--)
{
DataRowView dataRow = (DataRowView)dgv.SelectedItems[i];
dataRow.Delete();
}

C#: How do you make sure that a row or item is selected in ListView before performing an action?

What is the best way to check if there is atleast a selected item in a listview or not in an if statement?
I'm not entirely sure what you are asking. Do you want to make sure at least 1 item is selected before running an action? If so the following should work
if ( listView.SelectedItems.Count > 0 ) {
// Do something
}
Or are you curious if a particular item is selected? If so try the following
if ( listView.SelectedItems.Contains(someItem)) {
// Do something
}
if( listView.SelectedItems.Count > 0 ){
// do stuff here
}
You can also check the value of a selected item or perhaps bind it to a string if needed:
//Below is with string
String member = (String)ListView1.SelectedValue;
//Below is with any class
AnyClass member = (AnyClass)ListView1.SelectedValue;
String StaffID = member.StaffID;
int taskId = Convert.ToInt32(itemRow.SubItems[0].Text);
string taskDate = itemRow.SubItems1.ToString();
string taskDescription = itemRow.SubItems[2].ToString();enter image description here
//Here a simple loop that go through all the items in the list
for (int i = 0; i < listView1.Items.Count; i++)
{
//checks if the item in the list has the value true to the properties checked
if (listView1.Items[x].Checked == true)
{//your code
//e.g.
listView1.Items[x].Checked = false;
}
}
You can also check count of the selected item list by using getCheckedItemCount() method of the listview. for example,
if( listview.getCheckedItemCount() > 0 ) {
// do stuff here
}

Categories