How to precheck the checkbox of Bound CheckBoxList?

O

oshiko

Hi All,

Below is my SQL Statement,

Select Text, Value, Status from Tables

I want to mark as a checked when the Status is true, how do I achieve this
during databinding?

Thank you very much.

Regards,
Oshiko
 
V

Vlad Iliescu

I don't think you can do this with a CheckBoxList. You might want to
use a Repeater, or a DataList.

<asp:DataList ID="DataList1" runat="server" DataKeyField="Value">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1"
runat="server" Checked='<%# Eval("Status") %>' Text='<%# Eval("Text")
%>' />
</ItemTemplate>
</asp:DataList>
 
M

MS

Hi
you need to do it urself... either by looping through List items .... Like

for( ..... to Listitems lenth......)
{
list.items.add(new listitem(datatable.rows[colname].....)
if(datatable.rows[colname] == '1')
{
list.items.selected=true;
}
}

best ofluck.. Munawar Hussain
 
E

Eliyahu Goldin

Oshiko,

I don't think you can do it during databinding. You can rather loop through
the dataset and set the Selected property for the items depending on the
Status column value.

Eliyahu
 
A

andrew

Here is a chontrol i made to handle this problem. You need to have
your datasource provide a field with as a checked/unchecked value when
databinding. You set the DataCheckedField value to the name of this
field. So you may have to handle your select statements a little
different than normal. Here is the source althought, feel free to mail
me if you have questions. This control is derived from checkboxlist
control.
This is control is quiered off the selected value of a gridview.

<AspNetHostingPermission(SecurityAction.Demand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
AspNetHostingPermission(SecurityAction.InheritanceDemand, _
Level:=AspNetHostingPermissionLevel.Minimal), _
DefaultProperty("Text"), _
ToolboxData("<{0}:MegaCheckBoxList
runat=server></{0}:MegaCheckBoxList>")> _
Public Class MegaCheckBoxList
Inherits System.Web.UI.WebControls.CheckBoxList

Private _checklist As New ArrayList
'---------------------------------------------------
' PROPERTIES
'---------------------------------------------------
<Category("Data"), DefaultValue(""),
TypeConverter(GetType(String))> _
Public Property DataCheckedField() As String
Get
Dim o As Object
o = ViewState("DataCheckedField")

Return o
End Get
Set(ByVal value As String)
ViewState("DataCheckedField") = value
End Set
End Property

<Category("Apperance"), DefaultValue(""),
TypeConverter(GetType(String))> _
Public Property CheckedCssClass() As String
Get
Dim o As Object
o = ViewState("CheckedCssClass")

Return o
End Get
Set(ByVal value As String)
ViewState("CheckedCssClass") = value
End Set
End Property


Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs)
MyBase.OnPreRender(e)
Try
For i As Integer = 0 To Items.Count() - 1
If _checklist(i) Then
CType(MyBase.Items(i), ListItem).Selected = True
End If
Next
Catch
End Try
End Sub

Public Sub CheckAll()
For Each item As ListItem In Items
item.Selected = True
Next
End Sub


Protected Overrides Sub RenderItem(ByVal itemType As
System.Web.UI.WebControls.ListItemType, ByVal repeatIndex As Integer,
ByVal repeatInfo As System.Web.UI.WebControls.RepeatInfo, ByVal writer
As System.Web.UI.HtmlTextWriter)

If Me.Items(repeatIndex).Selected Then
writer.Write("<div class='" & CheckedCssClass & "'>")
MyBase.RenderItem(itemType, repeatIndex, repeatInfo,
writer)
writer.Write("</div>")
Else
MyBase.RenderItem(itemType, repeatIndex, repeatInfo,
writer)
End If

End Sub

Protected Overrides Sub PerformDataBinding(ByVal dataSource As
System.Collections.IEnumerable)
Try
MyBase.PerformDataBinding(dataSource)

Dim e As IEnumerator = dataSource.GetEnumerator

While e.MoveNext()
_checklist.Add(DataBinder.GetPropertyValue(e.Current,
DataCheckedField))
End While
Catch
End Try

End Sub

End Class


----------------------------------------------
I use the control something like this.

<MCS:MegaCheckBoxList ID="chklstMapping" runat="server"
DataSourceID="sqldsBulletinDepartment"
Width="100%"
RepeatColumns="3"
RepeatLayout="Table"
DataTextField="DepartmentName"
DataValueField="DepartmentID"
DatacheckedField="Checked"
CssClass="CleanDetailsView" CellPadding="5" CellSpacing="5"
DataTextFormatString=" {0}"
Enabled="True"
CheckedCssClass="CheckedItems" >
</MCS:MegaCheckBoxList>

---------------------------------

<asp:SqlDataSource ID="sqldsBulletinDepartment" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString%>"
SelectCommand="sp_GetDepartmentsByBulletinID"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="gvBulletins"
Name="BulletinID" PropertyName="SelectedValue"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>

--------------------------------------------
And my Stored Procedure looks like
-- =============================================
-- Author: Andrew Boudreau
-- Create date: 3/14/2006
-- Description: Gets the departments for a given bulletin with
-- Checked column set to true. This is used for megacheckbox.
-- =============================================
ALTER PROCEDURE [dbo].[sp_GetDepartmentsByBulletinID]
@BulletinID INT
AS
BEGIN
SET NOCOUNT ON;
SELECT D.DepartmentID, D.DepartmentName,
CASE
WHEN (SELECT COUNT(*)
FROM DepartmentToBulletin DTB
WHERE DTB.DepartmentID = D.DepartmentID AND
DTB.BulletinID = @BulletinID) > 0 THEN 1
ELSE 0
END as Checked
FROM Department AS D
ORDER BY D.DepartmentName
END


So, that should give you an idea of everything you need for a
pre-checked checkbox list that is bindable. Good luck, let me know if
you have questions. Ohh yeah, the class doesn't really have any good
error handling but it seems to work for now. The real trick on the
databinding comes into play in Protected Overrides Sub
PerformDataBinding(ByVal dataSource As
System.Collections.IEnumerable) which allows us to easily change the
way the datafield is binding, plus this can work with datasourceid or
datasource. Pretty sweet, thanks .net 2.0! I know you're suppose to
use html writers and what not but i'm still learning, so go easy on me
please.

Thanks,
Andrew
 
Joined
Sep 26, 2006
Messages
1
Reaction score
0
Thanks to Andrew, adapted the CheckBoxList Custom Control in C#

Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Security.Permissions;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SomeCustomControlsLibrary
{
    [
    AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal),
    DefaultProperty("Text"),
    ToolboxData("<{0}:CheckBoxListGR runat=\"server\"> </{0}:CheckBoxListGR>")
    ]
    public class CheckBoxListGR : CheckBoxList
    {
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        ArrayList _checklist;

        [
        Category("Data"),
        DefaultValue(""),
        Description("Boolean field in the datasource which provides the value for the Checked property of the checkboxes.")
        ]
        public string DataCheckedField
        {
            get
            {
                String s = (String)ViewState["DataCheckedField"];
                return ((s == null) ? String.Empty : s);
            }
            set
            {
                ViewState["DataCheckedField"] = value;
            }

        }

        protected override void PerformDataBinding(IEnumerable data)
        {
            base.PerformDataBinding(data);

            IEnumerator dataSourceEnumerator = data.GetEnumerator();

            _checklist = new ArrayList();

            // Iterate through the table rows.
            while (dataSourceEnumerator.MoveNext())
            {
                // Add the next data row to the ArrayList.
                _checklist.Add(
                    DataBinder.GetPropertyValue(dataSourceEnumerator.Current, DataCheckedField));
            }

            //Saves the selected values to trhe viewstate.
            ViewState["_checklist"] = _checklist;
        }

        protected override void OnPreRender(EventArgs e)
        {
            // Run the OnPreRender method on the base class.
            base.OnPreRender(e);

            //Retrieves the selected values from the viewstate.
            if (_checklist == null) _checklist = (ArrayList)ViewState["_checklist"];

            for (int i = 0; i < Items.Count; ++i)
                if ((bool)_checklist[i] == true)
                    ((ListItem)base.Items[i]).Selected = true;
        }
    }
}

That wasn't deeply tested, but fits for basic use, such as :

HTML:
<cc1:CheckBoxListGR ID="CheckBoxListGR1" runat="server"
    DataCheckedField="Selected" DataSourceID="ObjectDataSource1"
    DataTextField="Lib" DataValueField="Id">
</cc1:CheckBoxListGR>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
  SelectMethod="GetData"
  TypeName="DataSetGetTagsAdapters.GetTagsTableAdapter"> </asp:ObjectDataSource>

And then...

Code:
        foreach (ListItem li in CheckBoxListGR1.Items)
        {
            if (li.Selected)
            {
              //Do some very interesting stuf...
            }
        }

Have a nice day, and thanks to Andrew !

Greg

- I'm still not a compiler
 
Joined
Jun 22, 2007
Messages
1
Reaction score
0
Greg and Andrew,

Thanks for your code, it´s exactly what I needed: Much lighter than a grid view.

A small remark: on the PerformDataBinding method before trying to use de acessor put a test to see if data is not null.

Beside that the control runned very well with my ObjectDataSource.

Best regards,

JP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top