How to loop through dropdown items in a toolstrip - c#

I have a dropdown in my toolstrip (toolbar) i have attached a click event to each item in drop down as the dropdown has been populated dynamically, now i can casted the selected item in the dropdown and set its state to checked, to have a tick next to it, i wish to have a loop in another method to check which item has been checked. How do i loop through the items in the dropdown checking which item is checked?
foreach (DataSet1.xspLibraryByNameRow libName in data.xspLibraryByName)
{
var name = new LibraryItems(libName);
if (libName.xlib_Code != "NULL")
{
catDrpDwn.DropDown.Items.Add(name);
catDrpDwn.DropDown.Tag = name;
name.Click += new EventHandler(name_Click);
}
}
}
void mapArea_VE_MapReady(object sender, EventArgs e)
{
loadPoints();
}
void name_Click(object sender, EventArgs e)
{
var selected = (LibraryItems)sender;
selected.Checked = true;
loadPoints();
}

foreach (var items in catDrpDwn.DropDown.Items)
{
var it = (LibraryItems)items;
if (it.Checked == true)
{
}
}

Try this
var items=catDrpDwn.DropDown.Items.Cast<LibraryItems>().Where(d=>d.Checked).ToList();
here you will get all checked items and you can loop into it.

Related

how to check whether items present in list box & how to check list box has duplicates? in csharp

private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(textBox1.Text);
}
private void button2_Click(object sender, EventArgs e)
{
string val = listBox1.Text.Trim();
if (listBox1.Items.Contains(val)) {
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
else
{
MessageBox.Show("There is no items present");
}
}
elements are entered from text box to list box, If entered the same data,. how to check? or msg box should display and
while deleting items from the list box if there is no items how to i get to know.
You can check if the value entered in the textbox is already in the listbox or not:
bool listContainsItem = Listbox.Items.Any(item => item.Value == textboxValue);
if(listContainsItem)
{
// ... item is in listbox, do your magic
}
else
{
// ... item is not in listbox, do some other magic
}
You can do this in the Onchange event of your textbox, or when clicking a button, ... give us more context so we can provide you a better solution.
You can use a HashSet as data source to make sure your list contains unique elements.
In example :
HashSet<string> ListBoxSource = new HashSet<string>();
private void button2_Click(object sender, EventArgs e)
{
string val = listBox1.Text.Trim();
// ListBoxSource.Add(val) Return true if val isn't present and perform the adding
if (ListBoxSource.Add(val))
{
// DataSource needs to be a IList or IListSource, hence the conversion to List
listBox1.DataSource = ListBoxSource.ToList();
}
else
{
MessageBox.Show("Item is already in list");
}
}
You may check for duplicated item by looping through each item in the list to be compared with name of item to be added when add button is clicked:
private void addBtn_Click(object sender, EventArgs e)
{
bool similarItem = false;
if (!String.IsNullOrEmpty(itemText.Text.Trim()))
{
foreach (string listItem in itemListBox.Items)
{
if (listItem == itemText.Text)
{
MessageBox.Show("Similar item detected");
similarItem = true;
break;
}
}
if(!similarItem)
itemListBox.Items.Add(itemText.Text);
}
}
To prompt user when delete button is clicked when there is no item, the selected index will be -1, u may use that as the condition to prompt user:
private void deleteBtn_Click(object sender, EventArgs e)
{
if (itemListBox.SelectedIndex > -1)
itemListBox.Items.RemoveAt(itemListBox.SelectedIndex);
else
MessageBox.Show("No item exist in the list box, operation fail");
}

I need to add the selected item of a combo box to the end of selected item in the list box

This is the data in the list box, from a database
Johnie Black
Sarah Smith
Carol Willis
Maggie Dubois
This is the data in the combo Box
(M)
(F)
I want to select a name in the listbox then when I proceed to select the gender from the comboBox the value I select must be added to the end of the name that is selected
example.
Carol Willis(F)
This is what I have tried:
private void Form1_Load(object sender, EventArgs e) { this.namesTableAdapter.Fill(this.namesDataSet.names);
comboBox1.Items.Add("(M)");
comboBox1.Items.Add("(F)");
comboBox1.SelectedIndex = 0;
listBox1.SelectedIndex = 0;
}
//The code above loads the items into the comboBox
//For the lisbox I connected to the database using the option "Use Data Bound Items"
Any form of help will be appreciated
This should point you into the right direction:
public ListBox lbNames = new ListBox();
public ComboBox cbxGender = new ComboBox();
// combobox selected index changed event
private void cbxGender_SelectedIndex_Changed(object sender, EventArgs e)
{
// check if there are selected items
if(lbNames.SelectedItems.Count == 1 && cbxGender.SelectedItem != null)
{
// replace previous added gender
Regex.Replace(lbNames.SelectedItem.ToString(), #".+(\([MF]\))", "");
// append new gender
lbNames.Items[lbNames.SelectedIndex] = lbNames.SelectedItem.ToString() + cbxGender.SelectedItem.ToString();
}
}
Wasnt tested, just a hint.
listBox1.Items[listBox1.SelectedIndex] = listBox1.Items[listBox1.SelectedIndex] + comboBox1.SelectedItem.ToString();
Something like this could do the trick:
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in listView.SelectedItems)
{
if (comboBox.SelectedItem != null)
item.Text += " " + comboBox.SelectedItem.ToString();
}
}
Don't forget to double click/add the "SelectedIndexChanged" event in the properties of your ComboBox on form.

Select/Deselect All checkbox

I have a checkboxlist which gets its items from a sql table and change based on what is selected from a drop down menu. I'm trying to add another checkbox in that list which acts as a select/deselect all box. I've seen a few examples around this site, but nothing seems to work quite right.
Intended Functionality: When box is selected, all the other boxes are selected.
When box is un-selected, all the other boxes are selected.
When box is selected, if another box is then unselected, the select all box is unselected.
C#:
List<ListItem> toBeRemoved = new List<ListItem>();
//removes items when new item from dropdown is selected
for (int i = 1; i < CheckOpenTimesheets.Items.Count; i++)
{
toBeRemoved.Add(CheckOpenTimesheets.Items[i]);
}
for (int i = 0; i < toBeRemoved.Count; i++)
{
CheckOpenTimesheets.Items.Remove(toBeRemoved[i]);
}
lblOpenTimesheets.Text = "";
String sql = "sql statement here";
command.CommandText = sql;
command.Parameters.Add(new SqlParameter("userid", ddlActingAs.SelectedValue.ToString()));
SqlDataReader reader = command.ExecuteReader();
//Adds items to the checkboxlist
while (reader.Read())
{
ListItem item = new ListItem();
item.Text += reader.GetDateTime(0).ToString("MM/dd/yyyy") + " is open";
item.Value = reader["StartDate"].ToString();
CheckOpenTimesheets.Items.Add(item);
}
CheckOpenTimesheets.UpdateAfterCallBack = true;
reader.Close();
What I tried for the selection/deselection:
protected void select_DeselectAll(object sender, System.EventArgs e)
{
if (CheckOpenTimesheets.Items[0].Selected == true)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = true;
}
}
else
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = false;
}
}
}
ASP:
<anthem:CheckBoxList ID="CheckOpenTimesheets" OnSelectedIndexChanged="select_DeselectAll" runat="server" AutoPostBack="true" >
<asp:ListItem Text="Select/Deselect All" />
</anthem:CheckBoxList>
Edit: The problem seems to be the OnSelectedIndexChanged event firing when the checkboxes other than the select all one is selected.
Edit2: Made the select all checkbox separate from the checkboxlist. However, when trying to implement the feature where if a checkbox is unselected when the select all checkbox is checked, the select all checkbox is then deselected BUT all the others don't "deselect". This isn't happening though because the select all checkbox event fires.
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach (ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = chkAll.Checked;
}
}
protected void checkbox_Selected(object sender, EventArgs e)
{
chkAll.CheckedChanged -= chkAll_CheckedChanged;
foreach (ListItem item in CheckOpenTimesheets.Items)
{
if ((item.Selected = false) && (chkAll.Checked = true))
{
chkAll.Checked = false;
}
}
}
It sounds like you understand your issue. The problem comes when you click any other checkbox other than the first one. If the first is not checked and you check another checkbox, your logic is telling all of the other checkboxes to not be checked, including the one you just checked.
One option would be to take the "Select/Deselect All" checkbox out of the CheckBoxList. Let it be its own standalone checkbox.
<asp:CheckBox ID="chkAll" runat="server" Text="Select/Deselect All" OnCheckedChanged="chkAll_CheckedChanged" AutoPostBack="true" />
<anthem:CheckBoxList ID="checkOpenTimesheets" OnSelectedIndexChanged="checkOpenTimesheets_SelectedIndexChanged" runat="server" AutoPostBack="true" >
</anthem:CheckBoxList>
Then your select all event handler would just change them all to be the same.
protected void chkAll_CheckedChanged(object sender, EventArgs e)
{
foreach(ListItem item in CheckOpenTimesheets.Items)
{
item.Selected = chkAll.Checked;
}
}
Then also build in functionality where you programatically select or deselect the "Select/Deselect All" checkbox if any in the CheckBoxList change to something other than what all the others are. As explained in this answer, the key here would be to turn off the CheckedChanged event of the select all checkbox, otherwise that event will fire as you have seen.
protected void checkOpenTimesheets_SelectedIndexChanged(object sender, EventArgs e)
{
chkAll.CheckedChanged -= chkAll_CheckedChanged;
CheckBoxList checkOpenTimesheets = (CheckBoxList)sender;
if (allItemsCheckedInCheckBoxList(checkOpenTimesheets))
{
chkAll.Checked = true;
}
else if (allItemsUnCheckedInCheckBoxList(checkOpenTimesheets))
{
chkAll.Checked = false;
}
chkAll.CheckedChanged += chkAll_CheckedChanged;
}
private bool allItemsCheckedInCheckBoxList(CheckBoxList checkBoxList)
{
bool allItemsChecked = true;
foreach (ListItem item in checkBoxList.Items)
{
allItemsChecked = item.Selected;
if (!allItemsChecked)
break;
}
return allItemsChecked;
}
private bool allItemsUnCheckedInCheckBoxList(CheckBoxList checkBoxList)
{
bool allItemsUnChecked = false;
foreach (ListItem item in checkBoxList.Items)
{
allItemsUnChecked = item.Selected;
if (allItemsUnChecked)
break;
}
return allItemsUnChecked;
}

button click event to create new asp.net combobox

I have an existing drop down list(namely ddlA). On selecting a value in which, I am getting a cascading drop down list(ddlB). The requirement is, I need to create a button on the webform. By clicking the button, I would need to create drop down list dynamically of type ddlA. But here is the tricky part, I am required to present all the values in this dropdown except the selected value in the previous selection(s) of type ddlA.
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<DropDownList> DDLList = new List<DropDownList>();
Session["DDLs"] = DDLList;
}
else
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
//Add all existing DropDownLists to Panel
foreach (DropDownList dropdown in existingDropDowns)
{
Panel1.Controls.Add(dropdown);
dropdown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
}
Session["DDLs"] = existingDropDowns;
}
}
and here is my button click event code:
protected void ddlAdditionBtn_Click(object sender, EventArgs e)
{
List<DropDownList> existingDropDowns = (List<DropDownList>)Session["DDLs"];
DropDownList newDropDown = new DropDownList();
newDropDown.ID = "DDL" + existingDropDowns.Count.ToString();
existingDropDowns.Add(newDropDown);
Panel1.Controls.Add(newDropDown);
newDropDown.AutoPostBack = true;
Panel1.Controls.Add(new LiteralControl("<br/>"));
Session["DDLs"] = existingDropDowns;
}
Below is the code to connect the existing dropdown list with the database.
protected void GetDropDowndata()
{
DataTable ddlData= lookupCache.AccessLookupData(Constants.GroupSelectionFilter.ToString());
if (ddlData != null && ddlData.Rows.Count > 0)
{
ddlData.DefaultView.Sort = "DropDownValue";
ddlData = groupsData.DefaultView.ToTable();
ddlSelectGrp.DataSource = ddlData;
ddlSelectGrp.DataTextField = "DropDownValue";//ddlSelectGrp is the existing dropdown id
ddlSelectGrp.DataValueField = "DropDownBoxID";
ddlSelectGrp.DataMember = "DropDownGroup";
ddlSelectGrp.DataBind();
ddlSelectGrp.Items.Insert(1, Constants.GroupAll.ToString());
ddlSelectGrp.SelectedIndex = 1;
btnGroupSave.Enabled = true;
btnGroupSave.CssClass = "saveButton";
}
}
But I have no idea on how to connect the dynamically generated dropdownlist with the datasource and that too without the selected value(s) in the previous dropdown list(s).

Dynamically generate menustrip items

I have a database row with a primary key index and strUsername and I'm using these to dynamically generate dropdown items in a menu strip. The code gives the dropdown item the username string as it's text value and creates an event handler. I want to pass the primary key integer to the click event method but the code I've got gives all the click event methods the database row.count value. Can anyone help please?
// Generate drop down items from database
daUsers.Fill(dtUsers);
// Update mnuFileNew drop down list
if (dtUsers.Rows.Count != 0)
{
mnuFileNew.DropDownItems.Clear();
foreach (dbAutoBloggerDataSet.dbTblUsersRow row in dtUsers.Rows)
{
ToolStripMenuItem newItem = new ToolStripMenuItem(row.strUsername);
newItem.Click += new EventHandler((sender, e) => mnuFileNewUser_Click(sender, e, row.nId));
mnuFileNew.DropDownItems.Add(newItem);
}
}
// Drop down item event handler
private void mnuFileNewUser_Click(object sender, EventArgs e, int nId)
{
frmLogin frmLogin = new frmLogin(nId);
DialogResult result = frmLogin.ShowDialog();
if (result == DialogResult.OK)
{
frmProfile frmProfile = new frmProfile(frmLogin.nId);
frmProfile.ShowDialog();
screenRefresh();
}
}
I think this sample code is useful
void AddMenuItem(string text, string action)
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Text = text;
item.Click += new EventHandler(item_Click);
item.Tag = action;
//first option, inserts at the top
//historyMenu.Items.Add(item);
//second option, should insert at the end
historyMenuItem.DropDownItems.Insert(historyMenuItem.DropDownItems.Count, item);
}
private void someHistoryMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
string args = menuItem.Tag.ToString();
YourSpecialAction(args);
}

Categories

Resources