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...
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 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));
}
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;
}
I want to get value of row where checkbox is checked. I am new to C# windows forms and so far unsuccessful. I want to eventually use these row values, so if user selects multiple row and then I should get value for those checked. Also, I have set the selection mode to 'fullrowselect'
Please suggest changes to my code
private void button1_Click(object sender, EventArgs e)
{
StringBuilder ln = new StringBuilder();
dataGridView1.ClearSelection();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (dataGridView1.SelectedRows.Count>0 )
{
ln.Append(row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("No row is selected!");
break;
}
}
MessageBox.Show("Row Content -" + ln);
}
Having a check-box column in your grid will not change the internal status of any of the rows, so you will need to iterate over them all yourself to evaluate. This should do the trick, although you will need to provide the correct column index for the checkbox column in checkBoxColumnIndex
int checkBoxColumnIndex = nnn; // 0 based index of checkboxcolumn
private void button1_Click(object sender, EventArgs e)
{
List<string> checkedItems = new List<string>();
dataGridView1.ClearSelection();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCheckBoxCell checkBox= row.Cells[checkBoxColumnIndex] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(checkBox.Value) == true)
{
checkedItems.Add(row.Cells[1].Value.ToString());
}
}
if (checkItems.Count > 0)
MessageBox.Show("Row Content -\r\n" + String.Join("\r\n", checkedItems));
else
MessageBox.Show("No row is selected!");
}
Admittedly, the List<string> is a heavy construct if all you want to do is print the list, but it would be useful if you need to do further processing on all of the checked values.
The SelectedRows is the count of rows that are selected (or highlited rows), and not the rows that are checked.
The second problem in your code is that you're doing an foreach row, but inside you're using the dataGridView, and not the current row.
This is how your if must be:
private void button1_Click(object sender, EventArgs e)
{
const int checkBoxPosition = 3; //You must type here the position of checkbox.
// Remember, it's zero based.
StringBuilder ln = new StringBuilder();
dataGridView1.ClearSelection();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[checkBoxPosition].Value == true)
{
ln.Append(row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("No row is selected!");
break;
}
}
MessageBox.Show("Row Content -" + ln);
}
Here is a version of your code that may be what you want..but it is hard to tell because you are talking about selected rows but are clearing the selection before processing the rows!
That makes no sense.. maybe you mean the checked rows? OK, you do, so here you go:
private void button1_Click(object sender, EventArgs e)
{
StringBuilder ln = new StringBuilder();
dataGridView1.ClearSelection();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (((bool?)row.Cells[0].Value) == true)
{
ln.Append(row.Cells[1].FormattedValue);
}
}
if (ln.Length <= 0) MessageBox.Show("No rows are checked!");
else MessageBox.Show("Rows content: " + ln);
}
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;
}
}
}