Question : Preselect Checkboxlist Controls List Items based Based on matching DataTable Values

Hi All,

I have the following Checkboxlist control which shows a list of pages and their PageIDs from a DataTable (e.g. purposes - tbl1).

I have another DataTable (e.g. purposes - tbl2) that lists the PageIDs that should be pre-selected within the Checkboxlist.

Could anyone suggest how I could loop through the Checkboxlist ListItems and Check the boxes where PageIDs match?

Many thanks,

Rit
Code Snippet:
1:
2:


Answer : Preselect Checkboxlist Controls List Items based Based on matching DataTable Values

Try this..
Cheers
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
using System.Data; 

partial class TestPage : System.Web.UI.Page 
{ 
    
    protected void Page_Load(object sender, EventArgs e)
    { 
        //'Here goes the code to populate the checkbox list 
        DataTable dtDataTable = new DataTable(); 
        //'Consider this as ur table dt1 
        Int32 intCounter = default(Int32); 
        dtDataTable.TableName = "TestData"; 
        dtDataTable.Columns.Add("PageID", System.Type.GetType("System.Int32")); 
        dtDataTable.Columns.Add("MenuName", System.Type.GetType("System.String")); 
        
        for (intCounter = 1; intCounter <= 6; intCounter++) { 
            DataRow objRow = default(DataRow); 
            objRow = dtDataTable.NewRow(); 
            objRow.Item("PageID") = intCounter; 
            objRow.Item("MenuName") = "Page" + intCounter.ToString(); 
            dtDataTable.Rows.Add(objRow); 
        } 
        CheckboxPages.DataSource = dtDataTable; 
        CheckboxPages.DataBind(); 
        
        PreSelectCheckBoxListValues(); 
    } 
    
    private void PreSelectCheckBoxListValues() 
    { 
        DataTable dtPageIDs = new DataTable(); 
        //'Consider this as ur table dt2 
        Int32 intCounter = default(Int32); 
        dtPageIDs.Columns.Add("PageID", System.Type.GetType("System.Int32")); 
        for (intCounter = 4; intCounter <= 7; intCounter++) { 
            DataRow objRow = default(DataRow); 
            objRow = dtPageIDs.NewRow(); 
            objRow.Item("PageID") = intCounter; 
            dtPageIDs.Rows.Add(objRow); 
        } 
        
        foreach (DataRow drRow in dtPageIDs.Rows) { 
            if (((CheckboxPages.Items.FindByValue(drRow.Item("PageID").ToString())) != null)) { 
                CheckboxPages.Items.FindByValue(drRow.Item("PageID").ToString()).Selected = true; 
            } 
        } 
    } 
    
}
Random Solutions  
 
programming4us programming4us