views:

291

answers:

2

I have a Checkbox list in my page and its datasource set programatically in PreLoad() event:

protected void Page_PreLoad()
{
        if (!Page.IsPostBack)
        {
        CheckBoxList1.DataSource = NoK.AcceptedNoks((Guid)Membership.GetUser().ProviderUserKey);
        CheckBoxList1.DataTextField = "FullName";
        CheckBoxList1.DataValueField = "NoKId";
        CheckBoxList1.DataBind();
        }
foreach (ListItem chk in CheckBoxList1.Items)
{
    if (PrivateMessage.HasAccess(Request.QueryString["MessageId"], chk.Value))
    {
        chk.Selected = true;
    }
}

}

as you see in foreach will check for whether an item must be checked or Not. and it works nice. this means that end-user can Edit list Items and by default some of Item has been checked. now I want to get items by clicking a Button:

protected void UpdateRightBtn_Click(object sender, EventArgs e)
{
    var SelectedNokIds =
        CheckBoxList1.Items
        .OfType<ListItem>()
        .Where(li =>
            li.Selected == true)
            .Select(l => new Guid(l.Value));
}

but the Items in SelectedNokIds are still Old Items and if user change checkboxes no effect apeares in SelectedNokIds. Why???

Please Help!

A: 

It looks like it is because you are re-setting the values again at postback, effectively clearing the user's selection. You need to only initialize the values when it is not a postback.

driis
thanks for your answer but Unfotunatlly it is all you see no where re-setting Datasource. just in PerLoad().
mahdiahmadirad
A: 

Hey,

foreach (ListItem chk in CheckBoxList1.Items){ if (PrivateMessage.HasAccess(Request.QueryString["MessageId"], chk.Value)) { chk.Selected = true; }}

This line fires on every page load, so that would reset the selection (at least the ones that set selected to true). Shouldn't that be within !Page.IsPostback too? And in the update button, you could rebind there...

If you need to figure out what changed, you need to query the items in the data source again, and cross-reference those against the new selection list.

Brian