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
Related
Could someone help me with this problem I am having? I am trying to search through a listview for occurrences of a string inputted via a textbox and record the location index value. Now although the code could be improved... it works. The problem I am having is the loop doesn't iterate. The code only displays the first index value even if there are more than one occurrences.
Could someone show me how to get this loop to loop?
Thanks in advance...
foreach (ListViewItem item in listView1.Items){
foreach (ListViewItem.ListViewSubItem subItem in item.SubItems){
if (subItem.Text.ToLower().StartsWith(textBox1.Text.ToLower())){
var index = listView1.FindItemWithText(textBox1.Text.ToLower());
MessageBox.Show(listView1.Items.IndexOf(index).ToString());
count++;
}
}
}
You need to change this
var index = listView1.FindItemWithText(textBox1.Text.ToLower());
MessageBox.Show(listView1.Items.IndexOf(index).ToString())
to this
var index = item.Index;
MessageBox.Show(listView1.Items[index].ToString())
#johnny-mopp is correct that the finditemwithtext will only return one item, therefore it makes the loop completely redundant if you only wanted the first item.
Maybe something like this will work?
var index = listView1.Select(x=>x.IndexOf(textBox1.Text.ToLower(), StringComparison.Ordinal));
I have got a list box called lstPTLNameDHOD which has multiple PTL names which gets selected using Ctrl. I want to display the selected names in a label or some way that the person submitted the form can see who exactly they are submitting it for.
My problem is I can only get one name to display on the label.
// Items collection
foreach (ListItem item in lstPTLNameDHOD.Items)
{
if (item.Selected)
{
lbl1stPTL.Text = item.Value.ToString();
}
}
This is being called on post back on the reason dropdown being changed.
You are only getting one name to display because your current code would always display name of the last item that is selected.
I don't have a visual studio handy but you could try this:
StringBuilder sbText = new StringBuilder();
// Items collection
foreach (ListItem item in lstPTLNameDHOD.Items)
{
if (item.Selected)
{
lbl1stPTL.Text = sbText.Append(item.Value.ToString()).ToString();
}
}
You can probably refine this by adding a space or a comma between two item names but I hope you get the idea and it helps!
Again, sorry for not having VS handy!
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.
Using the approach shown in the question here, I am able to get the selected items values from my CheckBoxList:
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cbl.ID)
select Request.Form.Get(key);
I can then iterate over the results:
foreach (var item in selectedCheckBoxItems)
{
}
The problem is that item is just the posted value, which for a checkbox, is simply the string "on".
I need to be able to determine which item is "on", either by index or some other method.
Question: How do I determine which items in the CheckBoxList are selected, using Request.Form ?
Here is my CheckBoxList definition:
<asp:CheckBoxList runat="server" ID="cblAnimalType" SelectionMode="Multiple" DataTextField="OptionText" DataValueField="OptionId" AutoPostBack="True"/>
Items are added to the list from code behind:
DataTable dt = GetData(SqlGetListOptions, paramList);
cbl.DataSource = dt;
cbl.DataBind();
The other important thing to know is that ViewStateMode="Disabled", so I must use Request.Form to get the selected items.
In response to a comment, here is how the HTML for the CheckBoxList renders:
#Leopard pointed out that he sees values rendered in the HTML which is not occurring in my situation. AdamE's answer to this question explains why. I have the following line in web.config:
<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
which explains why I see "on" instead of the actual value of the selected items. I am not able to just yank the compatibility out of web.config without verifying it won't break something else, but it appears that if that setting is safe to remove, the checkbox list values will be accessible from codebehind.
As you are binding the checkboxList from Database with OptionId feild you can check which checkboxes are selected and store their value in List<int> assuming their value is int.
Then again when you populate the checkboxlist you can check which value is present in the list stored earlier and based on value you can select the relevant checkbox.
Here is a sample code
List<int> SelectedCheckBoxes = new List<int>();
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cblAnimalType.ID)
select Request.Form.Get(key);
foreach (var item in selectedCheckBoxItems)
{
SelectedCheckBoxes.Add(int.Parse(item.ToString()));
}
Then again when you populate the checkboxlist you can find the items by value and select them
foreach (ListItem listItem in cblAnimalType.Items)
{
if (SelectedCheckBoxes.Contains((int.Parse(listItem.Value))))
{
listItem.Selected = true;
}
}
You may need to store the SelectedCheckBoxes List in session depending on how you are populating the checkboxlist.
Update
As per discussion with you you were using Asp.net 4.0 but your checkboxes didn't have a value attribute which should have been there.
This is happening because you are using controlRenderingCompatibilityVersion="3.5" which is no longer needed as you are already using Asp.Net 4.0.
So removing this line from web.congif will solve the issue and you will be able to get the value of checkbox instead of just getting on
<pages controlRenderingCompatibilityVersion="3.5" />
I thought of one way to do it, by adding the key to the results. I'm not entirely happy with this method due to the string parsing that's required to get the index. Perhaps someone else has a better method?
The general idea is to add the key to the results:
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cbl.ID)
select new {Value = Request.Form.Get(key), Key = key};
foreach (var item in selectedCheckBoxItems)
{
var val = item.Value;
var key = item.Key;
}
I can then parse the key to find the index, which is what I need in order to set the selected option(s):
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cbl.ID)
select new {Value = Request.Form.Get(key), Key = key};
string[] stringParse = new string[] {listName.Replace(" ", "") + '$'};
foreach (var item in selectedCheckBoxItems)
{
var val = item.Value;
var key = item.Key;
var idxArray = key.Split(stringParse, StringSplitOptions.None);
var idxString = idxArray[idxArray.Length - 1];
int idxInt;
if (Int32.TryParse(idxString, out idxInt))
{
cbl.Items[idxInt].Selected = true;
}
}
Here is another way to parse the key to get the selected indexes. It also uses the UniqueID property to find the relevant keys.
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cblAnimalType.UniqueID)
select new { Value = Request.Form.Get(key), Key = key };
foreach (var item in selectedCheckBoxItems)
{
var val = item.Value;
string indexToken = item.Key.Replace(cblAnimalType.UniqueID, "");
int index = int.Parse(Regex.Replace(indexToken, #"[^\d]", ""));
...
}
I realize this is very close to previous responses so I am not sure if it is adding anything but it is a little more succinct so I will add it. In Request.Form.AllKeys, The Key is the html name of the checkbox. The html name of the checkbox contains the index. I would just change you linq query to only select the items that are "on" and then return the list of keys. After that you can just parse the keys to get the index.
var selectedCheckBoxItems = from key in Request.Form.AllKeys
where key.Contains(cbl.ID) && Request.Form.Get(key) == "on"
select key;
foreach (var item in selectedCheckBoxItems)
{
var index = 0;
if (int.TryParse(item.Substring(item.LastIndexOf("$") + 1), out index))
{
//do what you will
}
}
Also, string parsing in this instance is pretty safe since the field names are generated by the framework in a very specific and formulaic way. The odds of them ever being different are close to if not zero.
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())