How to return selected items from checkboxlist control in asp.net
I am trying to return in a string the selected items from a dynamically bound checkbox list control with no luck. I'm hoping someone can help. In my code behind file I am conencting to a class called users and building a datatable. I then bind the data table to the cblist control
private void populateUserList() //called on page load
{
SubmitOptions mySubmission = new SubmitOptions(juris, rptType, tmplName);
if (mySubmission.Users.Count == 0)
{
lbl_juris.Visible = false;
cb_selectUser.Visible = false;
lbl_AlertMsg.Visib开发者_如何学编程le = true;
btnSelect.Visible = false;
lbl_AlertMsg.Text = "No supervisors listed for jursidiction: " + juris.ToString();
}
else
{
dt.Columns.Add("Users");
for (int i = 0; i < mySubmission.Users.Count(); i++)
{
DataRow dr = dt.NewRow();
dr["Users"] = mySubmission.Users[i];
dt.Rows.Add(dr);
}
cb_selectUser.DataSource = dt;
cb_selectUser.DataBind();
}
}
Within the main aspx file I have the control defined as:
<asp:CheckBoxList ID="cb_selectUser"
Width="400px"
Height="100%"
AutoPostBack="false"
runat="server"
CellPadding="2"
CellSpacing="5"
DataTextField="Users"
DataValueField="Users"
>
</asp:CheckBoxList>
I have tried the following code where i itterate through the list but this only seems to work if I hard code values into the Checkboxt list as listitems.
protected void btn_returnUserList(object sender, System.Web.UI.ImageClickEventArgs e)
{
for (int i = 0; i < cb_selectUser.Items.Count; i++)
{
if (cb_selectUser.Items[i].Selected)
{
selectedUsers += cb_selectUser.Items[i].Text;
}
}
The list populates fine and all I want to do is return in a string all selected users from the checkbox list control.
As I said if I hard code the item values into the control the above code works and I can see the selected items in the string however removing the itemslist tags and switching over to a binding nothign happens. The above method counts the entire number of returns but nothing selected is ever returned.
Any tips or suggestions as to what I am missing would be greatly appreciated.
here is complete code of page working exactly as you want it. just add a CheckboxList to form name it to list1, add a button name it to btn and add a label and name it lbl.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var dt = new DataTable();
dt.Columns.Add("Users");
const string str = "User {0}";
for(var i=1;i<=10;i++)
{
//var r = dt.NewRow();
//r.ItemArray=new object[]{string.Format(str,i)};
dt.Rows.Add(new object[] {string.Format(str, i)});
}
list1.DataSource = dt;
list1.DataTextField = "Users";
list1.DataBind();
}
}
protected void btn_Click(object sender, EventArgs e)
{
var s = list1.Items.Cast<ListItem>()
.Where(item => item.Selected)
.Aggregate("", (current, item) => current + (item.Text + ", "));
lbl.Text = s.TrimEnd(new[] {',', ' '});
}
Are you sure populateUserList() is only being called once? (i.e. not on postback as well). If it gets called twice the selected items collection will be blank.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
populateUserList();
}
}
1- Download Jquery.json.js and add it to your view as refrence:
<script src="../../Scripts/jquery.json.js" type="text/javascript"></script>
2- I've added a ".cssMyClass" to all checkboxlist items so I grab the values by their css class:
<script type="text/javascript" >
$(document).ready(function () {
$("#btnSubmit").click(sendValues);
});
function populateValues()
{
var data = new Array();
$('.myCssClas').each(function () {
if ($(this).attr('checked')) {
var x = $(this).attr("value");
data.push(x);
}
});
return data;
}
function sendValues() {
var data = populateValues();
$.ajax({
type: 'POST',
url: '@Url.Content("~/Home/Save")',
data: $.json.encode(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function () { alert("1"); }
});
}
</script>
3- As you can see I've added all selected values to an Array and I've passed it to "Save" action of "Home" controller by ajax 4- in Controller you can receive the values by adding an array as argument:
[HttpPost]
public ActionResult Save(int[] val)
{
I've searched too much but apparently this is the only solution. Please let me know if you find a better solution for it.
string skills="";
for(int i=0;i<chkboxlist.Items.Count;i++)
{
if(chkboxlist.Items[i].Selected)
{
skills=skills+chkboxlist.Items[i].Text+",";
}
}
skills = skills.Remove(skills.Length-1);
lblResult.Text = skills.ToString();
You need to ensure your checkboxlist has databound before trying to retrieve values from it.
Can you use the sender to retrieve your selected items and see if you get the same result?
protected void btn_returnUserList(object sender, System.Web.UI.ImageClickEventArgs e)
{
CheckBoxList cbl = sender as CheckBoxList;
if (sender == null) {
throw new Exception("Sender is not a CheckBoxList");
}
for (int i = 0; i < cbl.Items.Count; i++)
{
if (cbl.Items[i].Selected)
{
// Also, set a breakpoint here... are you hitting this line?
selectedUsers += cbl.Items[i].Text;
}
}
Also, test to see if you're getting into the block for selected items... are they registering as selected, but not getting the text back? Or do the items not show up as selected in the first place?
Try out this one:-
foreach (ListItem li in cb_selectUser.Items)
{
//Your Code
}
I had same problem. You have to bind the CheckBoxList
as follows:
if(!IsPostBack)
{
//Bind your checkboxlist
}
精彩评论