Listbox in asp.net not getting selected items - c#

I have multiple dropdown & listbox in my webpage.
I am trying to get a list of CategoryID from a lstCatID listbox i am able to populate the listbox with category name.
If i remember correctly in first attempt my code worked fine, after that i made some change then it stated to always get the first item selected x No. of time
<asp:ListBox ID="lstCatID" runat="server" DataTextField="CategoryName"
DataValueField="CategoryID" SelectionMode="Multiple" CssClass="lstListBox">
</asp:ListBox>
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// Response.Write();
CatID += lstCatID.SelectedItem.Value + ",";
}
}
Response.Write(CatID);
}
I am not sure what is going wrong i checkd MSDN it show exactly the same way of doing it.
May be i am doing something wrong.
Just to add using firefox i am able to see multiple selected value have selected property.
<option value="3" selected="selected">One</option>
<option value="2">Two</option>
<option value="29" selected="selected">Three</option>
<option value="25" selected="selected">Four</option>
<option value="22" >Five</option>
My output in this case will be 3,3,3
I would appreciate help in this regard

I am not sure what is wrong with the logic i am using.
I came across a nice solution using LINQ.
This single statement works great & gets me the desired results.
string values = String.Join(", ", lstCatID.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray());
RESULT: 3,29,25

You are setting it to the same value every time:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// you are always using lstCatID.SelectedItem.Value.
CatID += lstCatID.SelectedItem.Value + ",";
}
}
When you actually want the value of the item in your loop that is selected:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// get the value of the item in your loop
CatID += li.Value + ",";
}
}

Try to add Page.IsPostback on your Page_Load like
protected void Page_Load(object sender, EventArgs e)
{
// Do your API code here unless you want it to occur only the first
// time the page loads, in which case put it in the IF statement below.
if (!Page.IsPostBack)
{
}
}
Code:
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected )
{
// TODO: Whatever you are doing with a selected item.
}
}
Response.Write(CatID);
}
Once i was facing the same problem and i made Postback mistake.
Hope it works.

Get the selected items using linq
var selected = lstCatID.Items.Where(i => i.Selected);

Minutes later I found a solution:
If lstLocations.Items.Count > 0 Then
For i As Integer = 0 To lstLocations.Items.Count - 1
If lstLocations.Items(i).Selected Then
'insert command
Dim selectedItem As String = lstLocations.Items(i).Text
End If
Next
End If
This worked fine in my scenario

Related

Deleting multiple checked items from an SQL bound checklist

So right now, I have tried the following code, however it only removes one list item. It seems that after it deletes the first item, the list refreshes and the other checked item does not get deleted. How can I go around this so that all the checked items are deleted from the DB Table?
//NewFoodInputTextBox is an ASP.NET TextBox which takes input
//just fine and outputs status/error updates as well.
protected void DeleteFoodButton_Click(object sender, EventArgs e)
{
try
{
int delCount = 0;
int prevDelCount = 0;
string status = "";
foreach (ListItem Item in FoodChecklist.Items)
{
if (Item.Selected)
{
FoodList.Delete(); //only deletes 1 item
prevDelCount = delCount;
delCount += 1;
if (delCount > prevDelCount) //printing out the deleted items
{
status = status + " " + Item.ToString(); //returns all checked items normally
}
}
}
if (delCount == 0)
{
NewFoodInputTextBox.Text = "Nothing selected to delete";
}
else
{
NewFoodInputTextBox.Text = "Deleted the following: " + status;
}
}
catch
{
NewFoodInputTextBox.Text = "Unexpected behavior detected";
}
}
Your problem is that you are using the Selected items, and not the Checked ones. These are 2 different things (selected is the blue highlight, checked is the checkbox). Use the Checked property in your condition and everything should work fine.
Side note, you could also use the CheckedItems property of the ListView in your foreach to simplify your code.
foreach (ListItem Item in FoodChecklist.CheckedItems)

How to get id of the selected item in combobox and populate another combobox with it?

I have 2 comboboxes created with Ajax Toolkit. One of them has a list of systems. I wanted to fill the other combobox with a list of subsystems whenever a system is selected. I did not use DisplayMember or ValueMember and most examples are using them.
.aspx side just in case:
<ajaxToolkit:ComboBox ID="cbox1" runat="server" OnSelectedIndexChanged="cbox1_SelectedIndexChanged" />
Is this doable with what I'm trying? Is the event I used correct for the situation?(I guess not,but other events seem to be unrelated) Let me show you the code:
protected void fillSystemCombo()
{
var sysOperations = new ModelOperations.ConstantSystem.ConstantSystemOperations();
var sys = sysOperations.GetSystemList().TransactionResultList;
foreach (var item in sys)
{
cbox1.Items.Add(item.description);
}
}
This works fine and I can see the systems in my first combobox.
This is what I tried for populating the second one:
protected void cbox1_SelectedIndexChanged(object sender, EventArgs e)
{
var subSysOperations = new ModelOperations.ConstantSubSystem.ConstantSubSystemOperations();
int index = Convert.ToInt32(cbox1.SelectedItem.Value);//i think this should get the id...
var subsys = subSysOperations.GetSubSystemList().TransactionResultList;
foreach (var item in subsys)
{
if (item.sysID == index)
{
cbox2.Items.Add(item.description);
}
}
}
sysID is the foreign key in SubSystem which is the ID of System. By the way, my SelectedIndexChanged event never fired when I was debugging the program even though I clicked on an item in combobox.
I've actually found the answer after carefully reading the parameters taken by Items.Add. It wants a ListItemso if I create a ListItem inside the loop I can finally add my items with both a Text and a Value like this:
foreach (var item in sys)
{
combo1.Items.Add(new ListItem { Text = item.description, Value = item.ID.ToString() });
}
After that I can get the index with
int index = Convert.ToInt32(combo1.SelectedValue);

Getting the selected values in a checkbox list

I have set up the following method when the checkbox list is checked.
protected void chk1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListItem list in chk1.Items)
{
if (list.Selected)
{
string name = list.Value.ToString();
}
}
}
I need to display the checked item from the checkbox list. However, for each iteration the selected attribute always comes false. It never satisfies the condition
if (list.Selected)
{
string name = list.Value.ToString();
}
How do I fix this?
Try something like this
var selectedListItems = chk1.Items.Cast<ListItem>().Where(x => x.Selected);
or in your case
var list = chk1.Items.Cast<ListItem>().Where(x => x.Selected);
now you will have a Collection that you can check / code against
also make sure that this code is being fired and or check if there is a PostBack
you can check this by checking if(!Is.PostBack){ }
My money is on you are re-binding the controls on every postback, instead do this:
if (!Page.IsPostBack)
{
// Only bind controls on initial page and let viewstate remember what the user did
}

Remove items from ListBox when DataSource is set

See I have a HashSet with several values, this values can contain for example numbers like 4141234567, 4241234567, 4261234567 and so on. I put a radioButton1 in my UserControl and I want when I click this just the numbers with 414 and 424 remains on my ListBox, for that I wrote this code:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
var bdHashSet = new HashSet<string>(bd);
if (openFileDialog1.FileName.ToString() != "")
{
foreach (var item in bdHashSet)
{
if (item.Substring(1, 3) != "414" || item.Substring(1, 3) != "424")
{
listBox1.Items.Remove(item);
}
}
}
}
But when I run the code I get this error:
Items collection cannot be modified when the DataSource property is set.
What is the proper way to remove the non wanted items from the list without remove them from the HashSet? I'll add later a optionButton for numbers that begin with 0416 and 0426 and also a optionButton to fill the listBox with original values, any advice?
try
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
var bdHashSet = new HashSet<string>(bd);
listBox1.Datasource = null;
listBox1.Datasource = bdHashSet.Where(s => (s.StartsWith("414") || s.StartsWith("424"))).ToList();
}
Try this:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
var bdHashSet = new HashSet<string>(bd);
listBox1.Datasource = bdHashSet.Select(s => (s.Substring(1, 3) == "414" || s.Substring(1, 3) == "424"));
//After setting the data source, you need to bind the data
listBox1.DataBind();
}
I think that you can select the elements with linq and then reassign the listBox with the result. In that way you dont need to remove elements from the list and you can keep the elements of the HashSet.
You can use BindingSource object. Bind it with DataSource and then use the RemoveAt() method.
Try this :
DataRow dr = ((DataRowView)listBox1.SelectedItem).Row;
((DataTable)listBox1.DataSource).Rows.Remove(dr);

making some items unselectable in dropdownlist using asp.net?

Dropdownlist i binded the values but in that dropdownlist just like group means(employee,nonemployee) so that items value is empty(""), so i can use databound event split the two fileds ,that two fields i can apply the color and underline and bould and user doesnot select that fields , so pls see the below code and modify this code.
protected void ddlconsultant_DataBound(object sender, EventArgs e) { foreach (ListItem item in ((DropDownList)sender).Items) {
string r = item.Value; if (r == "") {
item.Attributes.Add("style", "color:Red;font-weight:bolder"); } }
thanks
hemanth
I'm handling this situation on the client side, using javascript, actually jQuery
jQuery(document).ready(function () {
$("[id*=ddlConsultant] option[value='']").each(function () {
$(this).attr("disabled", "true");
$(this).css("color", "Red");
$(this).css("font-weight", "bolder");
});
});
It's probably easier to do this with server-side code, in the same place where you set the colour of list items:
item.Attributes.Add("style", "color:Red;font-weight:bolder");
item.Attributes.Add("disabled", "disabled");
This will product HTML code that looks something like this:
<option style="color:Red;font-weight:bolder" disabled="disabled">item text</option>
I know this is kinda an old question, but I've just been looking for the same information, and having just found out, thought I'd add the answer here for completeness.

Categories