Friday, 3 August 2012

ASP.Net Listbox with Checkbox - Get and Set Selected Value

I would recommend using a div styled like a listbox then we can have whatever we want in there.

<div style="width:200px; height:150px; padding:2px; overflow:auto; border: 1px solid #ccc;">
    <asp:CheckBoxList class="BodyTxt" ID="ChkServicestopitch" runat="server">
          <asp:ListItem Text="ERP" Value="1"></asp:ListItem>
          <asp:ListItem Text="CRM" Value="2"></asp:ListItem>
          <asp:ListItem Text="E-Commerce" Value="3"></asp:ListItem>
          <asp:ListItem Text="Business Intelligence" Value="4"></asp:ListItem>
          <asp:ListItem Text="HRMS" Value="5"></asp:ListItem>
          <asp:ListItem Text="Mobile Application" Value="6"></asp:ListItem>
          <asp:ListItem Text="Web Application" Value="7"></asp:ListItem>         
    </asp:CheckBoxList>
 </div>

The div containing the checkbox is shown as follows,

 
 











Getting the selected value and text from checkbox list,

string strText = "";
string strValue = "";
//GET THE SELECTED VALUE FROM CHECKBOX LIST
for (int i = 0; i < ChkServicestopitch.Items.Count; i++)
{
if (ChkServicestopitch.Items[i].Selected)
      {
            if (strText.Length == 0)
            {
                  strText = ChkServicestopitch.Items[i].Text;
                  strValue = ChkServicestopitch.Items[i].Value;       
            }
            else
            {
                  strText += "," + ChkServicestopitch.Items[i].Text;
                  strValue += "," + ChkServicestopitch.Items[i].Value;
            }
       }
}
lblResult.Text = "Checkbox Selected Text : " + strText + "</br> Checkbox Selected Value : " + strValue;

Output :


Set the selected value in Checkbox list based on passing the value,

//SET THE SELECTED VALUE IN CHECKBOX
string strValue = "1,3,4,5";
string[] splitStrValue = strValue.Split(',');
for (int i = 0; i < splitStrValue.Length; i++)
{
for (int j = 0; j < ChkServicestopitch.Items.Count; j++)
{
if (splitStrValue[i].ToString() == ChkServicestopitch.Items[j].Value.ToString())
{
ChkServicestopitch.Items[j].Selected = true;
}
}
}

Here i would pass the value as 1,3,4,5.

Output : 













Clear the selected checkbox value,

for (int j = 0; j < ChkServicestopitch.Items.Count; j++)
{
ChkServicestopitch.Items[j].Selected = false;
}
 


 

No comments:

Post a Comment