Select/Deselect All checkbox - c#

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

Related

All select /deselect button

enter image description hereI want to make n 'all select' button in datagridview.
datagirdview has checkbox column.
If I press the Select All button, I can select the entire selection.
If I press the Select All button again, I want to release the entire selection.
I can only Select All, no DeSelect All .
Please help me :(
private void Btn_selectall_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in dataGridView1.Rows)
{
item.Selected = true;
item.Cells[0].Value = true;
}
}
You can invert the values like so
item.Selected = !item.Selected;
item.Cells[0].Value = !item.Cells[0].Value;
You could try something like this:
private void Btn_selectall_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Cast<DataGridViewRow>().All(r => r.Selected))
{
// deselect all
foreach (DataGridViewRow item in dataGridView1.Rows)
{
item.Selected = false;
item.Cells[0].Value = false;
}
}
else
{
// select all
foreach (DataGridViewRow item in dataGridView1.Rows)
{
item.Selected = true;
item.Cells[0].Value = true;
}
}
}

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).

Get new dropdownlist boxes On button click in asp.net c# with different Ids and assign datasource, along with selection changed functionality

I need to generate 3 DropDownList Boxes in a row Dynamically on ADD Button click event. Once the DDL is generated i should be able to assign Data source to it and also do DDL-selectedEventChanged functionality on them in c# asp.net.
Below link was exactly am looking for but i couldn't assign data source or i couldn't do any functionality
"Adding multiple DropDownLists with a button click"
any better Ideas please help
if i press Button i need to get 3 DDLs at a time, if i press again it should generate again, so number of clicks= no. of rows with three DDL's in each row
Here is the sample code. The only trick is that you need to load those dynamic controls again after post back. Otherwise, you won't be able to access those.
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
<asp:Button runat="server" ID="AddButton" OnClick="AddButton_Click" Text="Add" />
private List<int> _controlIds;
private List<int> ControlIds
{
get
{
if (_controlIds == null)
{
if (ViewState["ControlIds"] != null)
_controlIds = (List<int>)ViewState["ControlIds"];
else
_controlIds = new List<int>();
}
return _controlIds;
}
set { ViewState["ControlIds"] = value; }
}
private List<string> DataSource
{
get { return new List<string> { "One", "Two", "Three" }; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
var dataSource = DataSource;
foreach (int id in ControlIds)
{
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}
}
protected void AddButton_Click(object sender, EventArgs e)
{
var dataSource = DataSource;
for (int i = 0; i < 3; i++)
{
var reqs = ControlIds;
int id = ControlIds.Count + 1;
reqs.Add(id);
ControlIds = reqs;
var ddl = new DropDownList();
ddl.ID = id.ToString();
foreach (var data in dataSource)
ddl.Items.Add(new ListItem(data));
PlaceHolder1.Controls.Add(ddl);
}
}

How to loop through dropdown items in a toolstrip

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.

c# List view focus problem

I have a listview which display the content from the database.I also have a refresh button in my form.Once the refresh button is clicked the listview is get updated once again.The problem is when the refresh button is clicked the already selected item in the listview is get removed from the focus.This is my code
private void btnRefresh_Click(object sender, EventArgs e)
{
//to refresh manually
this.Refresh();
listView1.Items.Clear();
/*btnEdit_Question.Enabled = true;
btnRepeat_Question.Enabled = true;
btnDelete_Question.Enabled = true;*/
GetData();
}
public void GetData()
{
try
{
now = DateTime.Now;
String time_date = now.ToString();
myConnection = new SqlConnection(connectString);
listView1.Items.Clear();
myConnection.Open();
String MyString1 = string.Format("SELECT " + data_variables.RES_TXT_STRING_COLUMN1 + "," + data_variables.RES_TXT_STRING_COLUMN2 + "," + data_variables.RES_TXT_STRING_COLUMN3 + "," + data_variables.RES_TXT_STRING_COLUMN4 + "," + data_variables.RES_TXT_STRING_COLUMN6 + " FROM " + data_variables.RES_TXT_STRING_QUESTION_TABLE);
com = myConnection.CreateCommand();
com.CommandText = MyString1;
dr = com.ExecuteReader();
ListViewItem itmX;
//Adding the Items To The Each Column
while (dr.Read())
{
itmX = new ListViewItem();
itmX.Text = dr.GetValue(0).ToString();
ListViewItem.ListViewSubItem aSubFooItem1 = new ListViewItem.ListViewSubItem(itmX, dr.GetValue(1).ToString()); //Creating subitems for the parent item
itmX.SubItems.Add(aSubFooItem1);
//Associating these subitems to the parent item
ListViewItem.ListViewSubItem aSubFooItem2 = new ListViewItem.ListViewSubItem(itmX, dr.GetValue(2).ToString()); //Creating subitems for the parent item
ListViewItem.ListViewSubItem aSubFooItem3 = new ListViewItem.ListViewSubItem(itmX, dr.GetValue(3).ToString()); //Creating subitems for the parent item
if (dr.GetValue(4).ToString() == "0")
{
aSubFooItem5 = new ListViewItem.ListViewSubItem(itmX, "No");
}
else
{
aSubFooItem5 = new ListViewItem.ListViewSubItem(itmX, "Yes");
}
if (dr.GetDateTime(2) < now && dr.GetDateTime(3) > now)
{
itmX.SubItems.Add(aSubFooItem2);
itmX.SubItems.Add(aSubFooItem3);
ListViewItem.ListViewSubItem aSubFooItem4 = new ListViewItem.ListViewSubItem(itmX, "In Progress");
itmX.SubItems.Add(aSubFooItem4);
itmX.SubItems.Add(aSubFooItem5);
}
else if (dr.GetDateTime(2) <= now)
{
itmX.SubItems.Add(aSubFooItem2);
itmX.SubItems.Add(aSubFooItem3);
ListViewItem.ListViewSubItem aSubFooItem4 = new ListViewItem.ListViewSubItem(itmX, "Expired");
itmX.SubItems.Add(aSubFooItem4);
itmX.SubItems.Add(aSubFooItem5);
}
else if (dr.GetDateTime(2) > now)
{
itmX.SubItems.Add(aSubFooItem2);
itmX.SubItems.Add(aSubFooItem3);
ListViewItem.ListViewSubItem aSubFooItem4 = new ListViewItem.ListViewSubItem(itmX, "Not Expired");
itmX.SubItems.Add(aSubFooItem4);
itmX.SubItems.Add(aSubFooItem5);
}
//add all the items ti listview
listView1.Items.Add(itmX);
//Adding colors
itmX.UseItemStyleForSubItems = false;
foreach (ListViewItem lvi in listView1.Items)
{
if (lvi.SubItems[4].Text=="Expired")
{
lvi.SubItems[4].BackColor = Color.Red;
}
else if (lvi.SubItems[4].Text == "Not Expired")
{
itmX.SubItems[4].BackColor = Color.Yellow;
}
else
{
itmX.SubItems[4].BackColor = Color.Green;
}
}
}
EventLog log = new EventLog(data_variables.RES_TXT_STRING_LOG_EVENT);
try
{
log.Source = data_variables.RES_TXT_STRING_LOG_SOURCE;
log.WriteEntry(data_variables.REX_TXT_STRING_MESSAGE_SUCCESSFUL, EventLogEntryType.Information);
}
if (listView_Selected_Index > -1)
{
//Keep the focus in the listview
this.listView1.Items[listView_Selected_Index].Focused = true;
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
now = DateTime.Now;
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
//Selecting the each values of the selected item from listview
listView_Selected_Index = listView1.SelectedIndices[i];
}
}
Can anyone help me how to remain the focus on the listview item even the refresh button is get clicked
You are removing original (some selected) items from the listview at the top of GetData().
You need to store somewhere what is selected before you read new data from database. Then after new data is displayed in listview you have to select items based on what was selected before data refresh.
//store selected items (id or sth else that identifies item)
GetData();
//restore selection (some of previously items may no longer exist)
In your code you only saving the last selected item not all of them.
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
//Selecting the each values of the selected item from listview
// here You are only saving last selected item
// instead of this do sth like
// selectedItems.Add(sth that identifies this item, not index)
listView_Selected_Index = listView1.SelectedIndices[i];
}
Also instead of doing it on every selectedIndexchanged You can do it only before data refresh unless you need it for some other reasons.
What you can do is, save the currently selected index of ListView1 in some temporary field and after calling GetData() method reset the selected index property of ListView1 by assigning value of temporary field to ListView1.SelectedIndex property
something like this:
private int _selectedIndex = -1;
private void btnRefresh_Click(object sender, EventArgs e)
{
_selectedIndex = listView1.SelectedIndex;
//to refresh manually
this.Refresh();
listView1.Items.Clear();
/*btnEdit_Question.Enabled = true;
btnRepeat_Question.Enabled = true;
btnDelete_Question.Enabled = true;*/
GetData();
listView1.SelectexIndex = _selectedIndex;
}

Categories

Resources