How to set multiple selected values in asp.net checkboxlist - asp.net

I have a asp.net checkbox list bound to a linq to sql datasource and when I check the item count of my CheckBoxList on the page load event it is 0. I want to be able to set the selected items on my checkboxlist here but cannot.
The datasource's selected event fires after the page load. If this is the case, how can I set the selected items on my list?
If I set the SelectedValue to a value it only displays the last value as selected instead of all the values which are selected. How can I select multiple values in my checkboxlist in the pageload event?

I know this is an old post but I had the same problem recently.
To select multiple items of a DataBound CheckBoxList, handle the DataBound event and loop through the Items collection setting the Selected property individually on each item as required.
Setting the SelectedValue property of the control only checks the final item.
foreach (ListItem item in MyCheckBoxList.Items)
{
item.Selected = ShouldItemBeSelectedMethod(item.Value);
}

Nice method I use:
private void SetCheckBoxListValues(CheckBoxList cbl, string[] values)
{
foreach (ListItem item in cbl.Items)
{
item.Selected = values.Contains(item.Value);
}
}

public void SetValueCheckBoxList(CheckBoxList cbl, string sValues)
{
if (!string.IsNullOrEmpty(sValues))
{
ArrayList values = StringToArrayList(sValues);
foreach (ListItem li in cbl.Items)
{
if (values.Contains(li.Value))
li.Selected = true;
else
li.Selected = false;
}
}
}
private ArrayList StringToArrayList(string value)
{
ArrayList _al = new ArrayList();
string[] _s = value.Split(new char[] { ',' });
foreach (string item in _s)
_al.Add(item);
return _al;
}
Thanks,
slnavn2000

Sounds like a Page Lifecycle - Databinding question.
You should really take a look at (the answers to) this question.

I used the DataBound event to select to set the selected items.

set checkboxlist selected items from a list:
List<int> yourlist;
//fill yourlist
foreach (ListItem item in checkboxlist.Items)
{
if (yourlist.Contains(int.Parse(item.Value.ToString())))
item.Selected = true;
}

Lets say your values are string array. Then I would do it this way
foreach (ListItem li in ctrl.Items)
li.Selected = Array.Exists(values, x => x == li.Value);

Related

Checkbox checked length in gridview using asp .net server side

I am having one gridview and check box for each row of gridview and one button outside gridview.
If I click on button then it should check for atmost one checkbox should be checked, otherwise it will display a message and return from loop.
But how to get the checkbox selected length in gridview in serverside.
If you just want to check if there is a checkbox checked in the gridview you can do this in the button:
bool isChecked = theGridview.Rows
.Cast<GridViewRow>()
.Any(a => ((CheckBox)a.FindControl("yourCheckbox")).Checked);
Do not forget using System.Linq;
You need to loop trough the row of the gridview and look for the checkbox as follows
foreach (GridViewRow r in YourGridView.Rows)
{
foreach(string cnt in controls){
int value = Convert.ToInt32(((System.Web.UI.HtmlControls.HtmlInputCheckBox)r.FindControl(cnt)).Value);
bool isChecked = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)r.FindControl(cnt)).Checked;
//now you have id and checked/unchecked. use your query to save it to database
}
}
Manipulate this according to you requirement.
foreach (GridViewRow gvrow in final.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("CheckBox1");
if (chk != null & chk.Checked)
{
//Perform action 1
}
else
{
// perform action-2
}

Binding multiple Dropdowns and textfields

In my project I have 2 dropdowns 1 listbox and 1 textbox. I Have already bound the 2 dropdowns together "PostalDropDown" and "CityDropDown" from the database and it works fine, Then i bind the listbox also to the previous dropdowns and it works fine also!
My question here i still have the last Textbox which i want it to display the name which is also bound to the results of dropdowns.
I cannot figur it out because the textbox does not have the SelectValue property, so I cannot assign it like i did with my dropdowns or listbox like i did:
if (!IsPostBack)
{
IEnumerable<Tuple<string, string, string, string>> data = GetData();
DropDownListPostal.DataSource = data.Select(tuple => tuple.Item1).Distinct().ToList();
DropDownListPostal.DataBind();
DropDownListCity.DataValueField = "Item1";
DropDownListCity.DataTextField = "Item2";
DropDownListCity.DataSource = data;
DropDownListCity.DataBind();
ListBox1.DataValueField = "item1";
ListBox1.DataTextField = "Item4";
ListBox1.DataSource = data;
ListBox1.DataBind();
}
}
and then i view the result on this on the selectedindexchanged on first dropdown:
protected void DropDownListPostal_SelectedIndexChanged1(object sender, EventArgs e)
{
//DropDownListPostal.ClearSelection();
ListBox1.ClearSelection();
DropDownListCity.ClearSelection();
var postal = DropDownListPostal.SelectedValue;
var listItem = DropDownListCity.Items.FindByValue(postal);
var street = ListBox1.Items.FindByValue(postal);
listItem.Selected = true;
street.Selected = true;
Can anyone show me how to add the rest of the database results on a textbox?
I can put the whole code for the page if you all want.
Cheers
If you really want to show all of the items in a Textbox which is quite strange you can display them comma seperated like this
TextBoxId.Text = String.Join(",", data.Select(op => op.Name));
Where Name is the property that contains the property you want to display in textbox
Edit
If you want to display the selected items of Listbox then loop on its item and check if the item is selected then display it in your textbox.
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
txtval.Text += " " + item.Text +"/"+ dropdowncity.SelectedItem.Text +"/"+ dropdownpostal.SelectedItem.Text;
}
}

Looping thru checkbox to determine checkbox id and see if this is checked

I have a requirement to loop through all checkboxes in ASP.Net page and determine the ID of the checkbox and process a logic if this is checked. Any pseudo code will help. Regards - Yagya
Use the ControlCollection of the form to loop through
foreach (Control ctl in Form.Controls)
{
if (ctl is CheckBox)
{
CheckBox chk = (CheckBox)ctl;
// Process chk as you wish
}
}
If you wish to check within any containers (panels etc), write the code in a recursive function like this one
void CheckControls(ControlCollection collection)
{
foreach (Control ctl in collection)
{
if (ctl is CheckBox)
{
CheckBox chk = (CheckBox)ctl;
//
}
if (ctl.Controls.Count > 0)
CheckControls(ctl.Controls); // Step into the container & check inside
}
}
Call the CheckControls with the Form's control collection
CheckControls(Form.Controls)
& it will step into all containers as well

Bind RadcomboBox with multiple columns from Datatable

I would like to bind 'Id', 'Name' and 'Email' from DataTable to RadComboBox. It's possible with ItemTemplate. But I don't want to display 'Email' column in the RadComboBox. I want display 'Email' in the label when the selectedIndexChanged. Is this possible?
Thank you..
Yes, you can bind these three items within the RadComboBox by using the template. Check out this demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx
Also, to display email when an item is selected, set the DataTextField="Email", which is the value that should appear when the selection is made.
HTH.
adding custom attributes to the RadComboBox is also a good option.
protected void RadComboBox_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
{
try
{
RadComboBox myRadComboBox = (RadComboBox)sender;
_rowsOfData = Db.getPeopleOfInterest();
foreach (row _row in _rowsOfData)
{
RadComboBoxItem item = new RadComboBoxItem
{
Text = _row.Name,
Value = _row.Id.ToString()
};
string eMail = _row.Email;
item.Attributes.Add("Email", Email);
item.DataBind();
}
}
catch (Exception ex)
{
HandleException(ex, true);
}
}
Then to display that on the GUI just use something like :
<td>
<%# DataBinder.Eval(Container, "Attributes['Name']")%>
</td>

With the ASP.NET GridView control, how can I disable controls or individual cells in a GridViewRow after PageIndexChanged?

I have a data bound GridView control, in which I am able to disable individual cells based on the User role. This only works on the first page.
private void LimitAccessToGridFields()
{
if (User.IsInRole("Processing")) return;
foreach (GridViewRow gridViewRow in gvScrubbed.Rows)
{
var checkBox = ((CheckBox) gridViewRow.FindControl("cbScrubbed"));
checkBox.Enabled = false;
// ButtonField does not have an ID to FindControl with
// Must use hard-coded Cell index
gridViewRow.Cells[1].Enabled = false;
}
}
I call this method on Page_Load, where it works. I've tried it in the PageIndexChaging and PageIndexChanged event handlers, where it doesn't work. While debugging, it appears to successfully set Enabled to false in both of the controls in the row. My goal is to disable these fields, depending on user role, after changing the page. How should this be accomplished?
You do not need to iterate through any controls to disable or hide/visible them.
Every cell in a GridView control is actually a HTML table reference, when rendered (look at the code in your page using FireFly or Inspector).
So why not iterate through all the cells, and any controls found within each cell, just disable them? Or you can simply loop through each row of your GridView and disable or hide it directly, which will affect everything inside the row.
Hiding using a Table Cell reference example:
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
{
TableCellCollection tbcCol = (TableCellCollection)gRow.Cells;
foreach (TableCell tblCell in tbcCol)
tblCell.Enabled = false;
}
}
So that will disable everything table cell by table cell.
OR.. why not just disable the entire row?
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
gRow.Enable = false;
}
If you need to pin-point or filter particular control types (CheckBox, TextBox, Label, etc) and only affect those controls then simply test for them!
foreach (GridViewRow gRow in myGridView.Rows)
{
if (gRow.RowType == DataControlRowType.DataRow)
{
TableCellCollection tbcCol = (TableCellCollection)gRow.Cells;
foreach (TableCell tblCell in tbcCol)
if (((TextBox)tblCell) != null)
((TextBox)tblCell).Enable = false;
}
}
I found that this must be done in the RowDataBound event handler.
if (e.Row.RowType == DataControlRowType.DataRow)
{
// details elided ...
// Limits the access to grid fields.
if (!User.IsInRole("PROCESSING"))
{
cbstuff.Enabled = false; // a checkbox
e.Row.Cells[1].Enabled = false; //a link button
}
}

Resources