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.
Related
I have to programmatically change a value in a GridView cell, depending on whether a compatible value exists or not in a populated List. If the value does exist, then take the value from a second List and modify the GridView cell value.
The logic would be as follows:
Check if the value of the list exists in the cell:
Get the corresponding value from the second list and set it as the Gridview cell value:
The code I was trying to implement is as follows:
if ((originalCombo.Count > 0) && (destinationCombos.Count > 0))
{
for (int k = 0; k < GridView1.Rows.Count; k++)
{
for (int i = 0; i < originalCombo.Count; i++)
{
for (int j = 0; j < destinationCombos.Count; j++)
{
if (GridView1.Rows[k].Cells[6].Text == originalCombo[i].ToString())
{
GridView1.Rows[k].Cells[6].Text = destinationCombos[j].ToString();
}
}
}
}
}
I think I have my entire logic wrong. Maybe I should use another method to iterate between the elements?
EDIT 1: So, probably I should be more clear about what I have and what I want to achieve. The originalCombo and destinationCombos are two lists, which are populated by a certain query. The GridView is already populated at the time I need to check for the value. So, if originalCombo and destinationCombos are not empty, I have to check the last cell on each row of the GridView, and if it's value is equal to one of the items of originalCombo,then I have to replace it with the respective value of destinationCombos
I'm populating a list from a LINQ Query, then I am using the list as the data source for a combo box.
I am then trying to select items within the combo box but it doesn't seem to be able to find the index
using (var db = new CruxEntities())
{
var query = from q in db.Businesses
where q.BusinessID == BusinessId
select q;
var B = query.FirstOrDefault();
if (B != null)
{
// other form controls populated
var sites = B.TblBusinessSites.ToList();
this.comboBox.DisplayMember = "SiteName";
this.comboBox.ValueMember = "BusinessSiteID";
this.comboBox.DataSource = sites;
int index = comboBox.FindString(B.IdFromLinq);
}
}
index always has the value of -1 assigned to it but i've stepped through the code and I know that the value exists in the list... it seems to be that the rest of the code is not recognising that the combo box has the values.
What am I missing?
Edit
I got the index fine... but something I missed out from my initial post is that there are 2 combo boxes bound to the list... I get the indexes for both of them fine when I step through the code but the combo boxes seem linked so I assigning the index to either one seems to assign it to both...
index = sites.FindIndex(s => s.BusinessSiteID == B.PrimarySiteDeliveryID);
comboBox_DefaultDeliverySite.SelectedIndex = index;
index = sites.FindIndex(s => s.BusinessSiteID == B.PrimarySiteInvoiceID);
comboBox_DefaultInvoiceSite.SelectedIndex = index;
You can't find site index because FindString method checks item's displayed text (site name in your case), but you are trying to search by ID, which is item's value.
Actually you even don't need to touch combobox here, because items will be added in same order as you have them in sites collection. To get index of some site you can just search index of site in sites list:
int index = sites.FindIndex(s => s.BusinessSiteID == B.IdFromLinq);
The FindString method is not a good choice, since you are binding with objects, so stick to object, not string.
You can loop on your item instead :
foreach(var item in comboBox.Items)
{
var businessSite = item as BusinessSite;
if(businessSite != null && businessSite.BusinessSiteID == B.IdFromLinq)
{
// your item here
}
}
Or index based:
for(int index = 0; index < comboBox.Items.Count; index++)
{
var item = comboBox.Items[index];
var businessSite = item as BusinessSite;
if(businessSite != null && businessSite.BusinessSiteID == B.IdFromLinq)
{
return index;
}
}
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.
In my WPF application I am browsing database in a datagrid. The point of my code is to store selected cells content in datagrid to some list of values for further operations. My code works well for selected items under 12, but for more items it throws an NullRefferenceException that says "
Object reference not set to an instance of an object".
Thank you for help.
code:
List<string> graphValue = new List<string>(dataGrid1.SelectedItems.Count); //create list
IList someList = new ArrayList(dataGrid1.SelectedItems); //define Ilist
DataGridColumn dataGridCol = dataGrid1.Columns[listBox1.SelectedIndex];
//select column whom i wana collect data
if (dataGrid1.SelectedItems != null) //when selection applied..
{
for (int i = 0; i < dataGrid1.SelectedItems.Count; i++) //go row by row in selected column above
{
try
{
id = ((TextBlock)dataGridCol.GetCellContent(someList[i])).Text.ToString(); //save cell content to string
graphValue.Add(id); //add value to Ilist
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message, "error"); }
}
}
}
This simple code may help you Here first we are going to loop through each record of Data-grid Then select specific cell/column data with loop by Providing Row , and Column as..
for(int row =0; row < dg_CountInventory.Rows.Count; row ++)
{
TextBlock b = dg_CountInventory.Columns[1].GetCellContent(dg_CountInventory.Items[row ]) as TextBlock;
}
When you define your someList with
IList someList = new ArrayList(dataGrid1.SelectedItems);
You actually create an ArrayList with all values are null. After that, you try to archive GetCellContent() method with it.
dataGridCol.GetCellContent(someList[i])).Text
someList[i] is probably null, that's why you get NullRefferenceException. Add some values of this array before use it.
I was googling and I found solution for me. I will give it here for the others. I would appreciate, if someone can explain me what I did wrong in the previous code upper.
This code works for me:
if (dataGrid1.SelectedItems.Count > 0) //when selection applied..
{
for (int i = 0; i < dataGrid1.SelectedItems.Count; i++) //go row by row in selected column above
{
try
{
System.Data.DataRowView selectedFile = (System.Data.DataRowView)dataGrid1.SelectedItems[i];
string str = Convert.ToString(selectedFile.Row.ItemArray[listBox1.SelectedIndex]);
graphValue.Add(str);
}
catch (Exception ex)
{ System.Windows.MessageBox.Show(ex.Message, "error"); }
}
Now I can select in DataGrid more rows than 10.
Refference to: http://www.codeproject.com/Questions/119505/Get-Selected-items-in-a-WPF-datagrid
Now I am really happy, thank you all for your time.
I currently have a CheckedListBox with several boxes. I want to be able to test every Checkbox in the list to see if it's checked, and if it is, add it's text value (CheckBox.Text) to a List of strings.
Here is what I have:
for ( int i = 0; i < multiTaskChecks.Items.Count; i++ )
{
if ( multiTaskChecks.GetItemChecked(i) )
{
checkedMultiTasks.Add(multiTaskChecks.GetItemText(i));
}
}
Using this, GetItemText is returning 0, 1, 2, 3, etc instead of the text values that I'm after. I have also tried CheckedListBox.Text.IndexOf(i), CheckedListBox.Text.ToList(), each without any luck.
I just cannot get the label text of one of these CheckBoxes from the CheckedListBox. Any help with this would be really appreciated.
Firstly, you should be able to loop through the checked items only like so
foreach (var item in multiTaskChecks.CheckedItems)
{
}
then depending on the type of the item, get whatever property you want from it. Sounds like it is just a Text or you just want the string, so
foreach (var item in multiTaskChecks.CheckedItems)
{
checkedMultiTasks.Add(item.ToString());
}
or I prefer
checkedMultiTasks.AddRange(multiTaskChecks.CheckedItems.
OfType<object>().Select(i => i.ToString()));
Try this:
for (int i = 0; i < multiTaskChecks.Items.Count; i++)
{
if (multiTaskChecks.GetItemChecked(i))
{
checkedMultiTasks.Add(multiTaskChecks.GetItemText(multiTaskChecks.Items[i]));
}
}
ListControl.GetItemText Method
NOTE There's a caution regarding DisplayMember for this method:
If the DisplayMember property is not specified, the value returned by GetItemText is the value of the item's ToString method. Otherwise, the method returns the string value of the member specified in the DisplayMember property for the object specified in the item parameter.
This should work:
var checkedMultiTasks = new List<string>();
foreach(var item in multiTaskChecks.CheckedItems) {
checkedMultiTasks.Add(item.ToString());
}