How to obtain the ListItem inside a CheckBoxList which triggered the postback?
I have two CheckBoxLists and I need to be able to set the ListItems selected in one of the CheckBoxList depending on the items selected in the other CheckBoxList.
How can I know which ListItem inside a CheckBoxList had issued the postback? The method must be run at server.
SOLUTION UPDATE:
Final solution i used (thanks to Four):
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedItem = CheckBoxList1.SelectedItem;
}
Where selectedItem is the ListItem that was click开发者_运维百科ed.
Set the AutoPostBack property to True and then make and changes you need to do on the server: How to use AutoPostBack feature in CheckBoxList
<asp:CheckBoxList
ID="CheckBoxList1"
runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChnaged"
>
To see which ListItems have been checked, you can iterate through the CheckBoxList as follows:
protected void CheckBoxList1_SelectedIndexChnaged(object sender, System.EventArgs e)
{
Label1.Text = "You Selected:<br /><i>";
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected == true)
{
Label1.Text += li.Text + "<br />";
}
}
Label1.Text += "</i>";
}
To get the value of the ListItem that was checked without iterating through all ListItems, you can do the following:
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
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])];
}
At this point you'll have the actual ListItem that was checked and you can do with it whatever you please.
Much simpler:
var selectedItem = CheckBoxList1.SelectedItem;
精彩评论