Where are the DataValueField values for a CheckBoxList stored?

I have this CheckBoxList on a page:

<asp:checkboxlist runat="server" id="Locations" datasourceid="LocationsDatasource"
   datatextfield="CountryName" datavaluefield="CountryCode" />

I’d like to loop through the checkbox elements on the client using Javascript and grab the value of each checked checkbox, but the values don’t appear to be available on the client side. The HTML output looks like this:
<table id="ctl00_Content_Locations" class="SearchFilterCheckboxlist" cellspacing="0" cellpadding="0" border="0" style="width:235px;border-collapse:collapse;">
<tr>
    <td><input id="ctl00_Content_Locations_0" type="checkbox" name="ctl00$Content$Locations$0" /><label for="ctl00_Content_Locations_0">Democratic Republic of the Congo</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_1" type="checkbox" name="ctl00$Content$Locations$1" /><label for="ctl00_Content_Locations_1">Central African Republic</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_2" type="checkbox" name="ctl00$Content$Locations$2" /><label for="ctl00_Content_Locations_2">Congo</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_3" type="checkbox" name="ctl00$Content$Locations$3" /><label for="ctl00_Content_Locations_3">Cameroon</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_4" type="checkbox" name="ctl00$Content$Locations$4" /><label for="ctl00_Content_Locations_4">Gabon</label></td>
</tr><tr>
    <td><input id="ctl00_Content_Locations_5" type="checkbox" name="ctl00$Content$Locations$5" /><label for="ctl00_Content_Locations_5">Equatorial Guinea</label></td>
</tr>

The values (“cd”, “cg”, “ga”, etc.) are nowhere to be found. Where are they? Is it even possible to access them on the client, or do I need to build this checkboxlist myself using a repeater or something?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I finally have the answer I’ve been looking for!

The asp.net CheckboxList control does in fact render the value attribute to HTML – it has been working for me in a Production site for over a year now! (We ALWAYS have EnableViewState turned off for all our sites and it still works, without any tweaks or hacks)

However, all of a sudden, it stopped working one day, and our CheckboxList checkboxes no longer were rendering their value attribute in HTML! WTF you say? So did we! It took a while to figure this out, but since it had been working before, we knew there had to be a reason. The reason was an accidental change to our web.config!

<pages controlRenderingCompatibilityVersion="3.5">

We removed this attribute from the pages configuration section and that did the trick!

Why is this so? We reflected the code for the CheckboxList control and found this in the RenderItem method:

if (this.RenderingCompatibility >= VersionUtil.Framework40)
{
    this._controlToRepeat.InputAttributes.Add("value", item.Value);
}

Dearest dev brothers and sisters do not despair! ALL the answers I searched for here on Stackexchange and the rest of the web gave erroneous information! As of .Net 4.0 asp.net renders the value attribute of the checkboxes of a CheckboxList:
<input type="checkbox" value="myvalue1" id="someid" />

Perhaps not practically useful, Microsoft gave you the ability to add a “controlRenderingCompatibilityVersion” to your web.config to turn this off by setting to a version lower than 4, which for our purposes is completely unnecessary and in fact harmful, since javascript code relied on the value attribute…

We were getting chk.val() equal to “on” for all our checkboxes, which is what originally alerted us to this problem in the first place (using jquery.val() which gets the value of the checkbox. Turns out “on” is the value of a checkbox that is checked… Learn something every day).

Method 2

<body>
     <form id="form1" runat="server">
          <div>
               <asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="tx" DataValueField="vl">
               </asp:CheckBoxList>
          </div>
          <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" /> 
     </form>
</body>
<script type="text/javascript">

function Button1_onclick() 
{
var itemarr = document.getElementById("CheckBoxList1").getElementsByTagName("span");
var itemlen = itemarr.length;
     for(i = 0; i <itemlen;i++)
     {
          alert(itemarr[i].getAttribute("dvalue"));
     }
return false;
}


</script>

Code
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("tx");
        dt.Columns.Add("vl");
        DataRow dr = dt.NewRow();
        dr[0] = "asdas";
        dr[1] = "1";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "456456";
        dr[1] = "2";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "yjryut";
        dr[1] = "3";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "yjrfdgdfgyut";
        dr[1] = "3";
        dt.Rows.Add(dr);
        dr = dt.NewRow();
        dr[0] = "34534";
        dr[1] = "3";
        dt.Rows.Add(dr);
        CheckBoxList1.DataSource = dt;
        CheckBoxList1.DataBind();
        foreach (ListItem li in CheckBoxList1.Items)
        {
            li.Attributes.Add("dvalue", li.Value);
        }
    }
}

Method 3

Stored in ViewState, you cannot access them on the client without some hacking.

Method 4

To avoid hacking the checkbox list just use a repeater as such:

<asp:Repeater ID="rptItems" runat="server" DataSourceID="odsDataSource">
<ItemTemplate>
<input id="iptCheckBox" type="checkbox" runat="server" value='<%# Eval("Key") %>'><%# Eval("Value") %></input>
</ItemTemplate>
</asp:Repeater>

Method 5

Had to do something really nasty in order to get this to work..

        <asp:Repeater ID="rptItems" runat="server">
            <ItemTemplate>
                <input ID="iptCheckBox" type="checkbox" runat="server" value='<%# Eval("your_data_value") %>' />
                <label ID="iptLabel" runat="server"><%# Eval("your_data_field") %></label>
                <br />
            </ItemTemplate>
        </asp:Repeater>

Codebehind:

Private Sub rptItems_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles rptItems.ItemDataBound
    Dim checkBox As HtmlInputCheckBox = DirectCast(e.Item.FindControl("iptCheckBox"), HtmlInputCheckBox)
    Dim label As HtmlControl = DirectCast(e.Item.FindControl("iptLabel"), HtmlControl)

    label.Attributes.Add("for", checkBox.ClientID)
End Sub

Method 6

Swapna, Your answer absolutely works. So in order to check if the check box in the ASP.Net Checkboxlist is checked and then accumulate the list as a comma-delimited string, you can do as

C# Code-behind

ChkboxList1.DataSource = dsData;
ChkboxList1.DataTextField = "your-display-column-name";
ChkboxList1.DataValueField = "your-identifier-column-name";
ChkboxList1.DataBind();

foreach (ListItem li in ChkboxList1.Items)
{
    li.Attributes.Add("DataValue", li.Value); 
}

Then in Javascript do
var selValues = "";
var ChkboxList1Ctl = document.getElementById("ChkboxList1");
var ChkboxList1Arr = null;
var ChkboxList1Attr= null;

if (ChkboxList1Ctl != null)
{
   ChkboxList1Arr = ChkboxList1Ctl.getElementsByTagName("INPUT");
   ChkboxList1Attr = ChkboxList1Ctl.getElementByTagName("span");
}
if (ChkboxList1Arr != null)
{
    for (var i = 0; i < ChkboxList1Arr.length; i++)
    {
       if (ChkboxList1Arr[i].checked)
           selValues += ChkboxList1Attr[i].getAttribute("DataValue") + ",";
    }
    if (selValues.length > 0)
       selValues = selValues.substr(0, selValues.length - 1);
}

Method 7

Removing <pages controlRenderingCompatibilityVersion="3.5"> caused an issue in some old code I was working on. I was getting this error. Once I got that error I realized it was too risky of a change.

To fix this, I ended up extending CheckBoxList and overriding the Render method to add an additional attribute containing the value to each list item:

public class CheckBoxListExt : CheckBoxList
{
    protected override void Render(HtmlTextWriter writer)
    {
        foreach (ListItem item in this.Items)
        {
            item.Attributes.Add("data-value", item.Value);
        }

        base.Render(writer);
    }
}

This will render the data-value attribute on the outer span tag.

Method 8

Easy Way I Do It.

//First create query directly From Database that contains hidden field code format (i do it in stored procedure)

SELECT Id,Name + '<input id="hf_Id" name="hf_Id" value="'+convert(nvarchar(100),Id)+'" type="hidden">' as Name FROM User

//Then bind checkbox list as normally(i bind it from dataview).

cbl.DataSource = dv;
cbl.DataTextField = "Name";
cbl.DataValueField = "Id";
cbl.DataBind();

//Then finally it represent code as follow.

<table id="cbl_Position" border="0">
<tbody>
<tr>
<td>
<input id="cbl_0" name="cbl$0" type="checkbox">
<label for="cbl_0">
ABC
<input id="hf_Id" name="hf_Id" value="1" type="hidden">
</label>
</td>
</tr>
</table>

This way you can get DataValueField as inside hiddenfield and also can get it value from client side using javascript.

Method 9

I tried the following and its working for me:

<asp:CheckBoxList ID="chkAttachments" runat="server"></asp:CheckBoxList>

Server side binding:
private void LoadCheckBoxData()
        {

            var docList = new List<Documents>(); // need to get the list data from database
                    chkAttachments.Items.Clear();

                    ListItem item = new ListItem();
                  
                    foreach (var doc in docList )
                    {
                        item = new ListItem();
                        item.Value = doc.Id.ToString();
                        item.Text = doc.doc_name;
                        chkAttachments.Items.Add(item);
                    }
                }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x