How can i take the value of selected checbkoxlist items that is filled by a string array? I use that code but it is only working if i filled checkboxlist from manually but if i filled it from database and then convert it into array and set to checkbox list it is not working.
Aspx form:
<div>
<asp:CheckBoxList ID="chkUsers" runat="server" >
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click1"
Text="Button" />
</div>
Cd file:
string s=string.Empty;
List<String> YrStrList = new List<string>();
// Loop through each item.
foreach (ListItem item in this.chkUsers.Items)
{
if (item.Selected)
{
// If the item is selected, add the value to the list.
YrStrList.Add(item.Value);
}
}
// s = j.ToString();
String YrStr = String.Join(";", YrStrList.ToArray());
Response.Write(String.Concat("Selected Items: ", YrStr));
While it's a bit hard to work out your exact scenario please have at look at the following example to see if it helps.
Markup:
<asp:CheckBoxList ID="chkUsers" runat="server" ></asp:CheckBoxList>
<asp:Button ID="SumitButton" runat="server" Text="Submit" OnClick="SumitButton_Click" />
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindData();
}
}
private void BindData()
{
string[] myArray = {"a","b","c"};
foreach (string item in myArray)
{
chkUsers.Items.Add(item);
}
chkUsers.Items[1].Selected = true;
}
protected void SumitButton_Click(object sender, EventArgs e)
{
var x = chkUsers.SelectedItem;
Response.Write(x);
}
I think you simply need to ask the checkboxlist what the selected item is?
var x = chkUsers.SelectedItem;
However, if this doesn't help please update your scenario and I'll take another look.
Lastly welcome.
Alternate BindData and submitclick options (these may better suit your needs)
private void BindData()
{
string[] myArray = {"a","b","c"};
var dt = new DataTable();
dt.Columns.Add("key");
dt.Columns.Add("value");
dt.Rows.Add(1,"a");
dt.Rows.Add(2,"b");
dt.Rows.Add(3,"c");
chkUsers.DataTextField = "value";
chkUsers.DataValueField = "value";
chkUsers.DataSource = dt;
chkUsers.DataBind();
}
protected void SumitButton_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkUsers.Items)
{
if (item.Selected)
Response.Write(item.Value);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.