C#-comparing combobox and that of the list items - c#

I have a combobox in which i can select three items and a list that contains items i want to check first of all whether the value selected from the combobox is in list and then the list item which is same as combobox one ; want to do some ops on it.
List<string>names = af.GetBlankSignatureNames();
comboBox1.SelectedItem.ToString();//combobox value taken
How to do so?

you can do:
if(names.Any(r=> r == comboBox1.SelectedItem.ToString())
{
// match found
}
else
{
// not found
}
Or to get the item from the list try:
string str = names.FirstOrDefault(r=> r == comboBox1.SelectedItem.ToString());
if str is null that means string not found in the names list, if its not null then you got the string as well, (which by the way would be same as comboBox1.SelectedItem.ToString())

Related

How to get the last selected index or value of checkboxlist

I am using one checkboxlist where i have to check the last selected item index or value.Below is one example:
As we can see in this image orange, pineapple, watermelon is selected. when i used to get this selected item using foreach loop i want to get the last selected item index.
As you didnt provided enough code , assuming that you already have the selectedchangedIndex method .
Try to update your SelectedChangedIndex As follows . This will give the Last selected value of checkboxlist
protected void yourcheckboxlistname_SelectedIndexChanged(object sender, EventArgs e)
{
string value = string.Empty;
string result = Request.Form["__EVENTTARGET"];
string[] checkedBox = result.Split('$'); ;
int index = int.Parse(checkedBox[checkedBox.Length - 1]);
if (yourcheckboxlistname.Items[index].Selected)
{
value = yourcheckboxlistname.Items[index].Value;
}
else
{
}
// For getting the list of values that are selected u can get it like
//this
int lastSelectedIndex = 0;
string lastSelectedValue = string.Empty;
foreach (ListItem listitem in yourcheckboxlistname.Items)
{
if (listitem.Selected)
{
int thisIndex = yourcheckboxlistname.Items.IndexOf(listitem);
if (lastSelectedIndex < thisIndex)
{
lastSelectedIndex = thisIndex;
lastSelectedValue = listitem.Value;
}
}
}
}
Do for loop then put the checked items on the string. The last string will give you the last item, then get its index. Assuming that your items are string in your CheckListBox:
string strGetLastItem = string.Empty;
foreach (object item in checkedListBox1.CheckedItems)
{
strGetLastItem = (string)item;
}
int index = checkedListBox1.Items.IndexOf(strGetLastItem);
//strGetLastItem will give you the last checked item.
//index will get the index of the item
You can create a List to hold the index of the item as its being checked. As an item gets checked, you add the index to the list. The last item checked will be the last index(int) in the list. This will let you know what was checked last.
var lastItemCheckedIndex = checkedItemsList.Count() - 1;
You also want to make sure that the logic that you write accounts for the scenario/event when the checkbox items are being unchecked. Every time an item is being unchecked you remove it from the list. If the last item on the list is removed then you will still be able to determine the last item that was checked prior.

c# select listview item if two listviews contains it

In my program I have 2 listviews and 1 button.
When I press the button, every listview item in the first listview will be selected in the second listview. The items in the first listview always exist in the second listview, but not the other way around.
I'm having trouble with selecting the items in the second listview. I'm trying to get the index with IndexOf.
foreach (ListViewItem item in firstListView.Items)
{
int index = secondListView.Items.IndexOf(item);
secondListView.Items[index].Selected = true;
}
I always get an error that index is -1 when I click the button. And I don't understand what I'm doing wrong.
SOLUTION
So what I tried to do here finding an index of an item which belongs to a different listview, and it doesn't work like that. Even though the text in both listviews are the same, the listview items are not identically the same because they are reference types.
I was not able to use the Text property because items could have the same text. So the solution I had was putting an unique integer in the Tag property for each ListViewItem. Since integers are value types, I can use that integer to check whether the ListViewItem in the first listview is in the second.
// Loop through each item in the first listview
foreach (ListViewItem item1 in firstListView.Items)
{
// For each item in the first listview, loop through the second listview to find if it's there
foreach (ListViewItem item2 in secondListView.Items)
{
// Check if item1 is identical to item2 by looking at its tag
if (int.Parse(item1.Tag) == int.Parse(item2.Tag))
{
// The item has been found and will be selected!
item2.Selected = true;
}
}
}
You can use such linq query to select items of the second list which exist in the first list too:
var items = from i1 in listView1.Items.Cast<ListViewItem>()
from i2 in listView2.Items.Cast<ListViewItem>()
where i1.SubItems.Cast<ListViewItem.ListViewSubItem>()
.Where((s, i) => s.Text != i2.SubItems[i].Text).Count() == 0
select i2;
items.ToList().ForEach(x => { x.Selected = true; });
Note:
When to try to use secondListView.Items.IndexOf method to find an item which belongs to the firstListView you can not expect it to find the item. The item you are trying to find its index, doesn't exists in second listview's item collection. You should find items using Text property of the item and sub items.
Well the same item obviously cant exist in two different lists.
If the text is the same, then try looking by it:
foreach (ListViewItem listViewItem in l1.Items)
{
var item = l2.Items.Cast<ListViewItem>().Where(lvi => lvi.Text == listViewItem.Text);
item.Selected=true;
}
Or:
foreach (ListViewItem listViewItem in l2.Items.Cast<ListViewItem>()
.Where(lvi => l1.Items.Cast<ListViewItem>().Any(lvi2 => lvi.Text == lvi2.Text))
{
listVieItem.Selected=true;
}
IndexOf returns -1 if it cannot find the object passed to it in the list. My guess is that you have an issue with your equality comparison. Do the objects in the lists implement IComparable? Otherwise they may not be finding the items correctly and are reverting to a bad equality comparison. ListViewItem may not be comparing how you expect.
you can try finding the item by text and then get the index like this
foreach (ListViewItem item in firstListView.Items)
{
var itm = secondListView.FindItemWithText(item.Text);
int index = secondListView.Items.IndexOf(itm);
secondListView.Items[index].Selected = true;
secondListView.Select();
}
what FindItemWithText will do is get the item in secondListView which will be of same name as in firstListView and IndexOf will get the index of item in secondListView
Edit
This solution is good when you have two lists whose items are same and does not include any repetition in name else if you have two items in secondListView with same name FindItemWithText will get the first item only.

Can not find index of combobox item when using a List as datasource

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;
}
}

Select multiple ListItems in an <asp:ListBox> from codebehind c#

I've got a ListBox(with selectionMode=multiple) and store the selected values in a cookie.
When the user comes back I want to provide him with all the options selected again.
What I do so far: I get all the selected values and store the indices ","-separated in a string in the cookie.
When the user comes back I split the string and loop through all ListItems to select each one again!
but with:
foreach (string str in selectedStr)
{
listbox1.SelectedIndex = Int32.Parse(str);
}
I only get one (random?) selected value.
Can anyone help me to get all the selected values selected again?
maybe even a better solution?
Just try using FindByValue property of Listview as follow...
foreach (string str in selectedStr)
{
if(listbox1.Items.FindByValue(str) != null)
{
listbox1.Items.FindByValue(str).Selected = true;
}
}
You can iterate through your splitted string array, and access the ListBox.Items[] based on the index and set the Selected property to true.
foreach (string str in selectedStr)
{
listbox1.Items[Int32.Parse(str)].Selected = true;
}
Make sure that str is indeed an integer and its in range with Items.Length

drop downlist selected value

ddlType.DataSource = ObjComplaintReportFormBLL.ComplaintType();
ddlType.DataTextField = "ComplaintType_Name";
ddlType.DataValueField = "complainttype_id";
ddlType.DataBind();
ddlType.Items.Insert(0, "All");
ObjComplaintReportFormBLL.ComplaintType() returns the ComplaintType_Name, complainttype_id
All is the default value for the drop down list Now how should I set the value of this list item "All" to 0(int)
I could do
ddlType.Items[0].value = "0". But this is a string
Thanks
Sun
Replace
ddlType.Items.Insert(0, "All");
with
ddlType.Items.Add(new ListItem(0,"All"));
By using Insert, you're putting the text "All" as the first option in the dropdown with a value of "" (empty string). To get "0" to be your value for your "All" item, provide a ListItem:
ddlType.Items.Add(new ListItem("0", "All"));
or, perhaps closer to what you want to do, this will insert your "All" item at the start of the list:
ddlType.Items.Insert(0, new ListItem("0", "All"));
then:
ddlType.SelectedValue = "0";
You can pass the listItem object to the ddlType.Items.Insert method instead of passing a string value e.g.
ListItem liItem = new ListItem("All","0");
ddlType.Items.Insert(0,liItem);

Categories