This question already has answers here:
How can I get the selected item of a dropdownlist, the first time my page loads?
(4 answers)
Closed 7 years ago.
I am trying to get all dropdownlists on my page, and in each of them the selected item text/value. But I am seem to be missing something.
foreach (DropDownList dr in this.Page.Form.Controls.OfType<DropDownList>()) {
foreach (ListItem li in dr.Items) {
if (li.Selected) {
//put the selected items value/text into something.
}
}
}
Any idea to do this?
Edit: To make it more clear. I have a random amount of DropDownLists, where i can select 1 option pr Dropdownlist. When I push a button, i need to get the information from what i have selected in each DropDownLists. (There is no ID on the DropDownLists, that there is a random number).
protected void Button1_Click(object sender, EventArgs e)
{
List<DropDownList> lst = new List<DropDownList>();
GetDropDownControls(GetListOfControlCollection(this.Form.Controls), ref lst);
foreach (DropDownList item in lst)
{
var selectedValue = item.SelectedValue;
//to do something with value
}
}
void GetDropDownControls(List<Control> controls, ref List<DropDownList> lst)
{
foreach (Control item in controls)
{
if (item.Controls.Count == 0 && item is DropDownList)
lst.Add((DropDownList)item);
else
if (item.Controls.Count > 0)
GetDropDownControls(GetListOfControlCollection(item.Controls), ref lst);
}
}
List<Control> GetListOfControlCollection(ControlCollection controls)
{
List<Control> result = new List<Control>();
foreach (Control item in controls)
{
result.Add(item);
}
return result;
}
Related
I have a function which clears all Comboboxes on the form and then try to update the text.
The new text is only shown if no Items are in the Item list.
Does anyone have an idea whats wrong?
I deleted all functions from the project so that only the necessary part is available.
https://www.dropbox.com/s/ibst7enrteyk9jb/Digitales_Auftragsformular.zip?dl=0
The project is attached. Simply start, go to tab "Werkzeuganfrage" there are two Comboboxes in red. One without Items = working, one with Items which is not working.
public Oberflaeche()
{
InitializeComponent();
List<ComboBox> myComboBoxes = GetControlsByType<ComboBox>(this, typeof(ComboBox));
foreach (ComboBox txt in myComboBoxes)
{
//txt.Text = "";
txt.SelectedIndex = -1;
}
Werkzeuganfrage_Combobox_rhino1_1.Text = "Rhino1_1";
Werkzeuganfrage_Combobox_rhino1_2.Text = "Rhino1_2";
comboBox1.Text = "Rhino1_1";
comboBox2.Text = "Rhino1_2";
}
public List<T> GetControlsByType<T>(Control container, Type type)
{
List<T> result = new List<T>();
foreach (Control c in container.Controls)
{
if (c.GetType() == type)
{
result.Add((T)Convert.ChangeType(c, typeof(T)));
}
if (c.HasChildren)
{
result.AddRange(GetControlsByType<T>(c, type));
}
}
return result;
}
I need to to use a checkboxlist because there is a unique case the user is allowed to select 3 items at the same time. Problem is that I can't even manage to get the single selection to work. I'm doing this is codebehind with an updatepanel to not refresh the page.
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
int count = 0;
int i = 0;
int maxObjects = cblCodeRequest.Items.Count;
string[] checkObjects = new string[maxObjects];
ListItem selectedItem = new ListItem();
foreach (ListItem item in cblCodeRequest.Items)
{
checkObjects[i] = item.Text;
i++;
}
foreach (ListItem item in cblCodeRequest.Items)
{
if (item.Selected)
{
count++;
selectedItem = item;
cblCodeRequest.ClearSelection();
}
foreach (ListItem itm in cblCodeRequest.Items)
{
if (item.Equals(selectedItem))
{
item.Selected = true;
}
}
}
}
I'm not sure how to proceed from here, i already save the selected item and clear the whole selection and then set it again but it doesn't do it, it just selects itself again after even if i click a different checkbox. I think my logic is messed up
Try this, Your foreach statements are not arranged correctly
protected void cblCodeRequest_OnSelectedIndexChanged(object sender, EventArgs e)
{
ListItem selectedItem = cblCodeRequest.Items[cblCodeRequest.SelectedIndex]
cblCodeRequest.ClearSelection();
int x = 0;
for(x; x<cblCodeRequest.Items.Count; x++)
{
if (cblCodeRequest.Items[x].Equals(selectedItem))
{
item.Selected = true;
}
}
}
Ok, I finally solved this problem. I had to dig through the problem with the debugger and follow the logic. I did this in jQuery so I can remove the update panel. If Anyone ever gets the same problem as me, this is the solution for you.
This allows you to use a checkboxlist like a radiobuttonlist but also allows you to check multiple checkboxes that belong to a special selection group.
$(function () {
$('[id*=cblCodeRequest] input').on('click', function () {
var checkboxlist = $('[id*=cblCodeRequest]'); // CheckBoxList
var checkboxArray = $('[id*=cblCodeRequest] input'); // CheckBoxList Items
var current = $(this); // Get Selected Checkbox
var label = $(current).next().text(); // Get CheckBox label name
// Uncheck every checkBox that don't match the unique multi selection combo
if (label != "Recâmbio" && label != "Série" && label != "Embalagem Alternativa") {
// Loop through checkboxArray and uncheck every item that does not meet the condition
$(checkboxArray).each(function (i) {
$(this).prop("checked", false);
});
// Check the selected item again
$(current).prop("checked", true);
} else {
// Get the current checkbox name
var chk = $(current).next().text();
// If the checkbox that matches the unique combo selection was click uncheck all invalid checkboxes that don't match
if (chk == "Série" || chk == "Recâmbio" || chk == "Embalagem Alternativa") {
// loop through the checkboxlist again
$(checkboxArray).each(function () {
// Get the looped item name
var ck = $(this).next().text();
// if checkbox does not belong to the unique combo selection, uncheck it
if (ck != "Recâmbio" && ck != "Série" && ck != "Embalagem Alternativa") {
$(this).prop("checked", false);
}
});
}
}
});
});
i have a dropdown list which i want to highlight a item from it. i have given the condition correct as par to me.But it didnt highlight the given item,instead showing normally as other items.
DataTable dtt = new DataTable();
dtt.Load(cmd.ExecuteReader());
ddlCompanyName.DataSource = dtt;
ddlCompanyName.DataTextField = "COMPANYNAME";
ddlCompanyName.DataValueField = "COMPANYID";
foreach (ListItem item in ddlCompanyName.Items)
{
if (item.Text == compidd)
{
item.Attributes.Add("style", "background-color:#3399FF;color:white;font-weight:bold;");
}
}
ddlCompanyName.DataBind();
ddlCompanyName.Items.Insert(0, new ListItem("--Select Name--"));
Compidd(string) has specified item to be highlighted in dropdownlist
You need to do DataBind before the loop:
ddlCompanyName.DataBind();
foreach (ListItem item in ddlCompanyName.Items)
{
if (item.Text == compidd)
{
item.Attributes.Add("style", "background-color:#3399FF;color:white;font-weight:bold;");
}
}
EDIT:
To set the value as default value you can try like this
ddlCompanyName.SelectedValue = "The value which you want to set as default"
The ddlCompanyName.DataBind(); must be executed before you loop the items:
ddlCompanyName.DataBind();
foreach (ListItem item in ddlCompanyName.Items)
{
if (item.Text == compidd)
{
item.Attributes.Add("style", "background-color:#3399FF;color:white;font-weight:bold;");
}
}
Otherwise there are no items in the DropDownList.
I am attempting to retrieve a ListItemCollection from a List of controls. This List contains many controls of different types - DropDownList, Label, TextBox.
I would like to retrieve all ListItem from all the DropDownList controls contained in the original List of controls.
My thought process so far has been to extract all of the DropDownList controls into a new list, and iterate though this to pull out each ListItem - however, every DropDownList control is coming up with 0 items
ControlCollection cList = pnlContent.Controls;
List<DropDownList> ddlList = new List<DropDownList>();
foreach (Control c in cList)
{
if (c.GetType() == new DropDownList().GetType())
{
ddlList.Add((DropDownList)c);
}
}
ListItemCollection itemCollection = new ListItemCollection();
foreach (DropDownList ddl in ddlList)
{
foreach(ListItem li in ddl.Items)
{
itemCollection.Add(li);
}
}
I'm sure this is the wrong (and massively inefficient) way of doing this. Any help would be appreciated.
This will do:
public IEnumerable<ListItem> GetListItems(ControlCollection controls)
{
return controls.OfType<DropDownList>().SelectMany(c => c.Items.OfType<ListItem>());
}
I currently do not have an installation where I can test this, but as a line of thought I would use Linq to do this.
Here is an example that you should be able to use;
var type = new DropDownList().GetType();
var listOfControl = from c in pnlContent.Controls
where c.GetType() == type
select ((DropDownList)c).Items;
Try this:
var ddlList = cList.OfType<DropDownList>();
ListItemCollection itemCollection = new ListItemCollection();
// option 1
var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li).ToArray();
itemCollection.AddRange(temp);
// or option 2
var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li);
foreach (var listItem in temp)
{
itemCollection.Add(listItem);
}
comboBox1.Items.Add(button1);
comboBox1.Items.Add(button2);
comboBox1.Items.Add(dateTimePicker1);
comboBox1.Items.Add(checkBox1);
comboBox2.Items.Add(button3);
comboBox2.Items.Add(button4);
comboBox2.Items.Add(dateTimePicker2);
comboBox2.Items.Add(checkBox2);
comboBox3.Items.Add(button5);
comboBox3.Items.Add(dateTimePicker3);
comboBox3.Items.Add(checkBox3);
comboBox3.Items.Add(checkBox4);
List<ComboBox> ddlList = new List<ComboBox>();
foreach (Control c in panel1.Controls)
{
if (c is ComboBox)
{
ddlList.Add((ComboBox)c);
}
}
List<Control> itemCollection = new List<Control>();
foreach (ComboBox ddl in ddlList)
{
foreach (var li in ddl.Items)
{
itemCollection.Add((Control)li);
}
}
Good day friends,
I got to know how we can make two checkboxes or checkboxes inside a checkbox list mutually exclusive.
However my question is little different from that, Hope to get some help from stack overflow,
Well I have two checkbox lists, as follows and from a dataset table I am getting the check box values,
CheckBoxlist1 - Checkbox_selectColumns
if (IsDataSetNotEmpty(ds))
{
CheckBox_selectColumns.Items.Clear();
foreach (DataRow row in ds.Tables[0].Rows)
{
CheckBox_selectColumns.Items.Add(row[0].ToString());
}
}
CheckBoxlist2 - Checkbox_selectFields
if (IsDataSetNotEmpty(ds))
{
Checkbox_selectFields.Items.Clear();
foreach (DataRow row in ds.Tables[1].Rows)
{
CheckBox_selectColumns.Items.Add(row[0].ToString());
}
}
I will get following checkboxes in each lists.
Checkbox_selectColumns : Employee ID, First Name, Last Name
Checkbox_selectFields : manager ID, Manager FName, Manager LName
Is there any way , I can make these two checkboxes mutually exclusive, That is if I select any one or more checkbox from first list, I should not select any checkboxes from second list and vice versa..
Thank you...
Rather than loop through the items in the CheckBox, I'd suggest using the SelectedValue property of the control, as that persists through postbacks (SelectedIndex does not) (ListControl.SelectedValue Property):
protected void CheckBox_selectColumns_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBox_selectColumns.SelectedValue != "")
{
foreach (ListItem listItem in CheckBox_SelectAll.Items)
{
listItem.Selected = false;
}
}
}
protected void CheckBox_SelectAll_CheckChanged(object sender, EventArgs e)
{
if (CheckBox_SelectAll.SelectedValue != "")
{
foreach (ListItem listItem in CheckBox_selectColumns.Items)
{
listItem.Selected = false;
}
}
}
Hi after working on this issue, with the help of Tim's tips, Finally got it worked. Please provide solutions, if you have any easy one .
protected void CheckBox_selectColumns_SelectedIndexChanged(object sender, EventArgs e)
{
bool Is_select = false;
foreach (ListItem listItem in CheckBox_selectColumns.Items)
{
if (listItem.Selected)
{
Is_select = true;
}
}
if (Is_select)
{
foreach (ListItem listItem in CheckBox_SelectAll.Items)
{
if (listItem.Selected)
{
listItem.slected=false;
}
}
}
}
For the second Checkbox List did the opposite..
protected void CheckBox_SelectAll_CheckedChanged(object sender, EventArgs e)
{
bool Is_select = false;
foreach (ListItem listItem in CheckBox_SelectAll.Items)
{
if (listItem.Selected)
{
Is_select = true;
}
}
if (Is_select)
{
foreach (ListItem listItem in CheckBox_selectColumns.Items)
{
if (listItem.Selected)
{
listItem.slected=false;
}
}
}
}
This one is working correctly, any suggestions to make the code bit more refined will be really helpful...