I have some working code, but I don't think it's the best way to achieve what I'm going for.
I have a CheckBoxList with 5 items - 4 individual items and 1 "Select All" item. When the Select All is selected, I want the other 4 to be checked off for the user. When the Select All is deselected, I want the other 4 to be unchecked for the user.
A bunch of things I've found on StackOverflow and Google simply suggest looping through CheckBoxList.Items, but this will not work for my case. For instance, say a user unchecked Item #3 - this would trigger the OnSelectedIndexChanged event, at which point I would begin looping through the Items. I would find that the "Select All" item is not selected, so I'd therefore deselect all items. Thus, a user would check off Item #3 only to have it be immediately deselected for them.
Below is my working code, but it uses some strange functions and I can't imagine that it's the best way to achieve what I'm looking for.
protected void StatusCheckBoxListChanged(object sender, System.EventArgs e)
{
//Crazy code I found online to determine which item triggered the event
CheckBoxList list = (CheckBoxList)sender;
string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
int index = control.Length - 1;
ListItem li = (ListItem)list.Items[Int32.Parse(control[index])];
if (li.ToString().Equals("Select All")) //If it was the "Select All" Item which triggered the event
{
//If it was checked, check off everything. If it was unchecked, uncheck everything.
for(int i = 0; i < StatusCheckBoxList.Items.Count; i++)
{
StatusCheckBoxList.Items[i].Selected = StatusCheckBoxList.Items.FindByValue("Select All").Selected;
}
}
}
you can try add field to you page that was show previous value for Select All like this
bool SelectAll;
init it in PageLoad event handler, something like this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback){
SelectAll = StatusCheckBoxList.Items.Cast<ListItem>().FirstOrDefault(d => d.Text == "Select All" && d.Selected) != null;
}
}
and change your event like this
protected void StatusCheckBoxListChanged(object sender, System.EventArgs e)
{
if(SelectAll != (StatusCheckBoxList.Items.Cast<ListItem>().FirstOrDefault(d => d.Text == "Select All" && d.Selected) != null)){
SelectAll = !SelectAll;
foreach(var li in StatusCheckBoxList.Items){
li.Selected = SelectAll;
}
}
}
NOTE: if you know position of item with "Select All" value you can do without LINQ something like this
Sample for case when "Select All" is first item
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostback){
SelectAll = StatusCheckBoxList.Items[0].Selected;
foreach(var li in StatusCheckBoxList.Items){
li.Selected = SelectAll;
}
}
}
and change your event like this
protected void StatusCheckBoxListChanged(object sender, System.EventArgs e)
{
if(SelectAll != StatusCheckBoxList.Items[0].Selected){
SelectAll = !SelectAll;
foreach(var li in StatusCheckBoxList.Items){
li.Selected = SelectAll;
}
}
}
I've worked around this in the past by setting a flag e.g.
public class MyClass
{
bool _IsReady = true;
protected void StatusCheckBoxListChanged(object sender, System.EventArgs e)
{
if (!_IsReady)
{
return;
}
//Crazy code I found online to determine which item triggered the event
CheckBoxList list = (CheckBoxList)sender;
string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
int index = control.Length - 1;
ListItem li = (ListItem)list.Items[Int32.Parse(control[index])];
if (li.ToString().Equals("Select All")) //If it was the "Select All" Item which triggered the event
{
SetAllStatusItemsSelected(StatusCheckBoxList.Items.FindByValue("Select All").Selected);
}
}
private void SetAllStatusItemsSelected(bool IsSelected)
{
_IsReady = false;
//If it was checked, check off everything. If it was unchecked, uncheck everything.
for(int i = 0; i < StatusCheckBoxList.Items.Count; i++)
{
StatusCheckBoxList.Items[i].Selected = StatusCheckBoxList.Items.FindByValue("Select All").Selected;
}
_IsReady = true;
}
}
I'd be interested to know if there is a more elegant way.
This the way I have always solved this issue
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
CheckBoxList lstBx = (CheckBoxList)sender;
List<ListItem> list = lstBx.Items.Cast<ListItem>().ToList();
string[] control = Request.Form.Get("__EVENTTARGET").Split('$');
int index = Convert.ToInt32(control[control.Length - 1]);
ListItem selectAllControl = list.FirstOrDefault(x => x.Text == "Select All");
ListItem selectAll = list.FirstOrDefault(x => x.Selected && x.Text == "Select All");
if (index == 0)
{
if (selectAll != null)
{
foreach (var item in list)
{
item.Selected = true;
}
}
}
else
{
if (selectAllControl != null)
{
selectAllControl.Selected = false;
}
}
}
Related
There are 4 values in my dropdown list, and if there is an "x" value in it, I want to hide that value. How can I do this using the If command.
protected void dr_alans_DataBound(object sender, EventArgs e)
{
if (dd_mainAlan.SelectedItem.Text == "Yƶnetici")
{
if (dr_alans.Items.FindByValue("22").Value=="22")
{
dr_alans.Items.FindByValue("22").Enabled = false;
}
else if (dr_alans.Items.FindByValue("23").Value == "23")
{
dr_alans.Items.FindByValue("23").Enabled = false;
}
}
}
If it is ASP.NET Forms, you should be able to do it like this maybe. This should hide the items with an x in the Value.
foreach (var itm in dd_mainAlan.Items)
{
var it = (ListItem)itm;
it.Enabled = !it.Value.Contains("x");
}
I am using C# and I need some help. I have DataGridView that I would like to filter (show/ hide columns) based on user selection from the CheckedListBox.
Inside the CheckedListBox, I have listed few items and those are the Column Names from the DataGridView:
All these columns are hidden by default.
CheckedListBox items
Now if user selects THERMAL, I would like to show THERMAL Column in DataGridView. If user deselects THERMAL, I would like to hide THERMAL Column in DataGridView. If user selects/ deselects multiple items, I would like to show/ hide all those items from the DataGridView. I hope this makes sense.
Here is the code that I have:
private void CLB_SHOW_HIDE_SelectedIndexChanged(object sender, EventArgs e)
{
string col = "";
for (int i = 0; i < CLB_SHOW_HIDE.CheckedItems.Count; i++)
{
if (col == "")
{
col = CLB_SHOW_HIDE.GetItemText(CLB_SHOW_HIDE.CheckedItems[i]);
this.DGV_FEATURE.Columns[col].Visible = true;
}
else
{
col += ", " + CLB_SHOW_HIDE.GetItemText(CLB_SHOW_HIDE.CheckedItems[i]);
this.DGV_FEATURE.Columns[col].Visible = false;
}
}
}
Here is the problem... If I remove else statement, I can show All the columns properly only if I go from the bottom up (see my picture above). If I go from top to the bottom, only first item would show. Then I would have to deselect that item and select another one in order for it to show.
If I add else statement like in above code, I get this
Error
Can anyone shed some light on this please?
Just figured out... For anyone that might look for solution similar to this, here is the code:
private void CLB_SHOW_HIDE_SelectedIndexChanged(object sender, EventArgs e)
{
int f = 0;
string qry = "";
for (int i = 0; i < CLB_SHOW_HIDE.Items.Count; i++)
{
if (CLB_SHOW_HIDE.GetItemChecked(i))
{
if (f == 1)
{
qry = CLB_SHOW_HIDE.Items[i].ToString();
this.DGV_FEATURE.Columns[qry].Visible = true;
}
if (f == 0)
{
qry = CLB_SHOW_HIDE.Items[i].ToString();
f = 1;
this.DGV_FEATURE.Columns[qry].Visible = true;
}
}
else
{
qry = CLB_SHOW_HIDE.Items[i].ToString();
this.DGV_FEATURE.Columns[qry].Visible = false;
}
}
}
You are looking for ItemCheck event.
For example, let's say, you have added some columns to DataGridView. Then you can setup checkedListBox and add column names to it. Also add an event handler to handle ItemCheck event:
foreach (DataGridViewColumn c in dataGridView1.Columns)
checkedListBox1.Items.Add(c.Name);
checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;
Then handle ItemCheck event to show or hide columns:
private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
var item = checkedListBox1.GetItemText(checkedListBox1.Items[e.Index]);
dataGridView1.Columns[item].Visible = e.NewValue == CheckState.Checked ? true : false;
}
I have a DataGridView with CheckBox column, my question is how do I get the data next to a checked checkboxes and assign them to a variables in array?
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (Convert.ToBoolean(this.dataGridView1.Rows[e.RowIndex].Cells["chkBoxColumn"].Value = true) == true)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
}
}
}
It prints the last checked item over and over.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (bool.Parse(dataGridView1.Rows[i].Cells["chkBoxColumn"].Value.ToString()) == true)
{
MessageBox.Show(dataGridView1.Rows[i].Cells[1].Value.ToString());
}
}
}
and i'm getting a null reference exception using this.
Edit
Question got changed, so tweaked the code so that the values get put into a list.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
List<string> someList = new List<string>();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
var cell = row.Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(cell.Value) == true)
{
if (cell.State != DataGridViewElementStates.Selected)
{
someList.Add(row.Cells[1].Value.ToString();
}
}
else if (cell.State == DataGridViewElementStates.Selected)
{
someList.Add(row.Cells[1].Value.ToString();
}
}
}
This might do the trick for you, however you'll get a popup every time a user ticks a checkbox, and you'll get as many popup as there are checkboxes that are true.
the problem is in the line
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
e.RowIndex points to the changed row
it should be:
for (int i = 0; i <= this.dataGridView1.Rows)
{
var row = this.dataGridView1.Rows[i]
if (Convert.ToBoolean(this.dataGridView1.Rows[i].Cells["chkBoxColumn"].Value = true) == true)
{
MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
}
}
Also, note that you're getting error in your second example because some row is containing a null value in the checkbox column.
Convert.ToBoolean(null) returns false
But bool.Parse(null) throws an exception
I guess something like this ?
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
Stringbuilder text = new StringBuilder();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["chkBoxColumn"].Value = true) == true)
{
text.Append(row.Cells[1].Value.ToString());
}
}
MessageBox.Show(text.ToString());
}
EDIT: the question has changed from showing the values to saving them into an array, so I need to change my answer also
Suppose you want all values for Cell[1] saved into an array
and suppose that cell is of type integer.
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
List<int> list = new List<int>();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["chkBoxColumn"].Value = true) == true)
{
list.Add(int.Parse(row.Cells[1].Value.ToString()));
}
}
// you now have all values saved into the list
}
You can put the code in a button click and find checked values this way:
private void button1_Click(object sender, EventArgs e)
{
var checkedValues = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells["Your CheckBox Column Name"].Value == true)
.Select(row => string.Format("{0}", row.Cells["The Other Column Name"].Value))
.ToList();
MessageBox.Show(string.Join(",", checkedValues));
}
Here is my code for the list of the items in a ListPicker. What I am trying to do is select one or more options and then after I press submit button I would like to display a MessageBox with the selected Items separated by commas. I also would like to store this value of the items selected to the database but, the first I am trying to do is populate the data into MessageBox.
lstPickerType.Items.Add("Aircrafts");
lstPickerType.Items.Add("Boats");
lstPickerType.Items.Add("Cars");
lstPickerType.Items.Add("Helicopters");
lstPickerType.Items.Add("Electric Powered");
lstPickerType.Items.Add("Gas Powered");
Here is the code that I have got to create a string from the list that is then displayed when the ListPicker is collapsed.
private void lstPickerType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
lstPickerType.SummaryForSelectedItemsDelegate = SummarizeItems;
}
private string SummarizeItems(IList items)
{
if (items != null && items.Count > 0)
{
string summarizedString = "";
for (int i = 0; i < items.Count; i++)
{
summarizedString += (string)items[i];
// if the item is not last coma is added
if (i != items.Count - 1)
summarizedString += ", ";
}
return summarizedString;
}
else
return "Nothing selected";
}
Finally for the button to display the MessageBox i have following code.
private void btnAddLocation_Click(object sender, RoutedEventArgs e)
{
foreach (var item in this.lstPickerType.SelectedItems)
{
var items = new List<object>();
MessageBox.Show(items.ToString());
}
I would really appreciate if anyone could help me to solve this issue. Thank You.
I'm a bit rusty of C#, and i don't have visual studio in this pc, but I would achieve your result without the selectionchanged event in the listpicker.
Trythis code in the button click:
Edit: a cast was missing.
private void btnAddLocation_Click(object sender, RoutedEventArgs e)
{
string r = "";
for (int i=0; i<this.lstPickerType.SelectedItems.Count; i++)
{
r += ((ListPickerItem)this.lstPickerType.SelectedItems[i]).Content;
if (i != this.lstPickerType.SelectedItems.Count - 1)
r += ", ";
}
MessageBox.Show(r);
}
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...