We help IT Professionals succeed at work.

Dropdownlist checkbox

VBdotnet2005
VBdotnet2005 asked
on
I am following this sample and kept getting error, not sure why.
http://www.dotnetspeaks.com/DisplayArticle.aspx?ID=63

Imports System.Data

Partial Class BCR_test_2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        Dim ddl As New DropDownList()
        ddl.ID = "ddlChkList"
        Dim lstItem As New ListItem()
        ddl.Items.Insert(0, lstItem)
        ddl.Width = New Unit(155)
        ddl.Attributes.Add("onmousedown", "showdivonClick()")
        Dim chkBxLst As New CheckBoxList()
        chkBxLst.ID = "chkLstItem"
        chkBxLst.Attributes.Add("onmouseover", "showdiv()")
        Dim dtListItem As DataTable = GetListItem()
        Dim rowNo As Integer = dtListItem.Rows.Count
        Dim lstValue As String = String.Empty
        Dim lstID As String = String.Empty
        For i As Integer = 0 To rowNo - 2
            lstValue = dtListItem.Rows(i)("Value").ToString()
            lstID = dtListItem.Rows(i)("ID").ToString()
            lstItem = New ListItem("<a href=""javascript:void(0)"" id=""alst"" style=""text-decoration:none;color:Black; "" onclick=""getSelectedItem(' " & lstValue & "','" & i & "','" & lstID & "','anchor');"">" & lstValue & "</a>", dtListItem.Rows(i)("ID").ToString())
            lstItem.Attributes.Add("onclick", "getSelectedItem('" & lstValue & "','" & i & "','" & lstID & "','listItem');")
            chkBxLst.Items.Add(lstItem)
        Next
        Dim div As New System.Web.UI.HtmlControls.HtmlGenericControl("div")
        div.ID = "divChkList"
        div.Controls.Add(chkBxLst)
        div.Style.Add("border", "black 1px solid")
        div.Style.Add("width", "160px")
        div.Style.Add("height", "180px")
        div.Style.Add("overflow", "AUTO")
        div.Style.Add("display", "none")
        phDDLCHK.Controls.Add(ddl)
        phDDLCHK.Controls.Add(div)
    End Sub

    Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn.Click

        Dim strSelectedItem As String = String.Empty
        Dim chk As CheckBoxList = DirectCast(phDDLCHK.FindControl("chkLstItem"), CheckBoxList)
        Dim ddl As DropDownList = DirectCast(Page.FindControl("ddlChkList"), DropDownList)
        For i As Integer = 0 To chk.Items.Count - 1
            If chk.Items(i).Selected Then
                If strSelectedItem.Length = 0 Then
                    strSelectedItem = chk.Items(i).Selected.ToString()
                Else
                    strSelectedItem = strSelectedItem & "," & chk.Items(i).Selected.ToString()
                End If
            End If
        Next
        ddl.Items.Clear()
        ddl.Items.Add(New ListItem(hidList.Value))
        lblSelectedItem.Text = strSelectedItem
    End Sub
    Public Function GetListItem() As DataTable
        Dim table As New DataTable()
        table.Columns.Add("ID", GetType(Integer))
        table.Columns.Add("Value", GetType(String))
        table.Rows.Add(1, "ListItem1")
        table.Rows.Add(2, "ListItem2")
        table.Rows.Add(3, "ListItem3")
        table.Rows.Add(4, "My ListItem Wraps also")
        table.Rows.Add(5, "My New ListItem5")
        table.Rows.Add(6, "ListItem6")
        table.Rows.Add(7, "ListItem7")
        table.Rows.Add(8, "ListItem8")
        Return table
    End Function

End Class




<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
      function showdiv() {
            document.getElementById("divChkList").style.display = "block";
      }

      function showdivonClick() {
            var objDLL = document.getElementById("divChkList");
            if (objDLL.style.display == "block")
                  objDLL.style.display = "none";
            else 
                  objDLL.style.display = "block";
      }


      function getSelectedItem(lstValue, lstNo, lstID, ctrlType) {
            var noItemChecked = 0;
            var ddlReport = document.getElementById("ddlChkList");
            var selectedItems = "";
            var arr = document.getElementById("chkLstItem").getElementsByTagName('input');
            var arrlbl = document.getElementById("chkLstItem").getElementsByTagName('label');
            var objLstId = document.getElementById('hidList');
            for (i = 0; i < arr.length; i++) {
                  checkbox = arr[i];
                  if (i == lstNo) {
                        if (ctrlType == 'anchor') {
                              if (!checkbox.checked) {
                                    checkbox.checked = true;
                              }
                              else {
                                    checkbox.checked = false;
                              }
                        }
                  }
                  if (checkbox.checked) {
                        if (selectedItems == "") {
                              selectedItems = arrlbl[i].innerText;
                        }
                        else {
                              selectedItems = selectedItems + "," + arrlbl[i].innerText;
                        }
                        noItemChecked = noItemChecked + 1;
                  }
            }
            ddlReport.title = selectedItems;
            var Text = ddlReport.options[ddlReport.selectedIndex].text;
            if (noItemChecked == 1)
                  ddlReport.options[ddlReport.selectedIndex].text = lstValue;
            else
                  ddlReport.options[ddlReport.selectedIndex].text = noItemChecked + " Items";
            document.getElementById('hidList').value = ddlReport.options[ddlReport.selectedIndex].text;
      }
      
      document.onclick = check;    
      function check(e) {
            var target = (e && e.target) || (event && event.srcElement);
            var obj = document.getElementById('divChkList');
            var obj1 = document.getElementById('ddlChkList');
            if (target.id != "alst" && !target.id.match("chkLstItem")) {
                  if (!(target == obj || target == obj1)) {
                        obj.style.display = 'none'
                  }
                  else if (target == obj || target == obj1) {
                        if (obj.style.display == 'block') {
                              obj.style.display = 'block';
                        }
                        else {
                              obj.style.display = 'none';
                              document.getElementById('ddlChkList').blur();
                        }
                  }
            }
      }
</script>


<table>
      <tr>
            <td valign="top" style="width: 165px">
                  <asp:PlaceHolder ID="phDDLCHK" runat="server"></asp:PlaceHolder>
            </td>
            <td valign="top">
                  <asp:Button ID="btn" runat="server" Text="Get Checked" OnClick="btn_Click" />
            </td>
            <td valign="top">
                  <asp:Label ID="lblSelectedItem" runat="server"></asp:Label>
            </td>
      </tr>
</table>
<asp:HiddenField ID="hidList" runat="server" />

</asp:Content>

Open in new window

ee.bmp
Comment
Watch Question

Commented:
ASP.NET control IDs don't actually correspond to the IDs that actually get put into the HTML.

The control is likely called ct100_divCheckList, but the best way to find out would be to use Firebug or Chrome and inspect the drop down element.

You'd need to change the var objDll = document.getElementById("divCheckList") to use the actual ID on the page.

Commented:
drain is right.


It should work out if you change this JS function:

      function showdivonClick(objID) {
            var objDLL = document.getElementById(objID);
            if (objDLL.style.display == "block")
                  objDLL.style.display = "none";
            else
                  objDLL.style.display = "block";
      }

AND change around your page load a little bit using the ClientID of the dynamically created div:

        Dim ddl As New DropDownList()
        ddl.ID = "ddlChkList"
        Dim lstItem As New ListItem()
        ddl.Items.Insert(0, lstItem)
        ddl.Width = New Unit(155)
        'ddl.Attributes.Add("onmousedown", String.Format("showdivonClick('{0}')", divChkList.ClientID))
        Dim chkBxLst As New CheckBoxList()
        chkBxLst.ID = "chkLstItem"
        chkBxLst.Attributes.Add("onmouseover", "showdiv()")
        Dim dtListItem As DataTable = GetListItem()
        Dim rowNo As Integer = dtListItem.Rows.Count
        Dim lstValue As String = String.Empty
        Dim lstID As String = String.Empty
        For i As Integer = 0 To rowNo - 2
            lstValue = dtListItem.Rows(i)("Value").ToString()
            lstID = dtListItem.Rows(i)("ID").ToString()
            lstItem = New ListItem("<a href=""javascript:void(0)"" id=""alst"" style=""text-decoration:none;color:Black; "" onclick=""getSelectedItem(' " & lstValue & "','" & i & "','" & lstID & "','anchor');"">" & lstValue & "</a>", dtListItem.Rows(i)("ID").ToString())
            lstItem.Attributes.Add("onclick", "getSelectedItem('" & lstValue & "','" & i & "','" & lstID & "','listItem');")
            chkBxLst.Items.Add(lstItem)
        Next
        Dim div As New System.Web.UI.HtmlControls.HtmlGenericControl("div")
        div.ID = "divChkList"
        div.Controls.Add(chkBxLst)
        div.Style.Add("border", "black 1px solid")
        div.Style.Add("width", "160px")
        div.Style.Add("height", "180px")
        div.Style.Add("overflow", "AUTO")
        div.Style.Add("display", "none")
        'This is the addition, it had to be moved to be in scope to get the id
        ddl.Attributes.Add("onmousedown", String.Format("showdivonClick('{0}');", div.ClientID))
        phDDLCHK.Controls.Add(ddl)
        phDDLCHK.Controls.Add(div)

Author

Commented:


errored

  function showdivonClick(objID) {
            var objDLL = document.getElementById(objID);
            if (objDLL.style.display == "block")  <<<<<<<< this line "Object required
                  objDLL.style.display = "none";
            else
                  objDLL.style.display = "block";
      }

Commented:
You might need to add the DIV to the phDDLCHK.Controls.Add(div) before you set the onmousedown?

If you do alert(objId) or use Firebug, what is the value of objID?

Commented:
Works fine for me with the exact code I posted. I was curious about whether the clientId would be assigned when creating a htmlgenericcontrol like this which is why I looked at this in the first place.

<see image>

Its possible that you didnt move the assignment of this line down to the same location as in my sample. The sequence of assignment change is important:

ddl.Attributes.Add("onmousedown", String.Format("showdivonClick('{0}');", div.ClientID))

Its possible that you rewrote it in a different way and made a syntax error.

Its possible that the clientID is somehow not being picked up properly (although I doubt it).

Put alert(objID); in there and see what is being displayed.

Copy/paste your updated code for review.




debug-block.jpg

Author

Commented:
Here is my entire code
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="test_2.aspx.vb" Inherits="abc_test_2" title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<script language="javascript" type="text/javascript">
      function showdiv() {
            document.getElementById("divChkList").style.display = "block";
      }

      function showdivonClick() {
            var objDLL = document.getElementById("divChkList");
            if (objDLL.style.display == "block")
                  objDLL.style.display = "none";
            else 
                  objDLL.style.display = "block";
      }


      function getSelectedItem(lstValue, lstNo, lstID, ctrlType) {
            var noItemChecked = 0;
            var ddlReport = document.getElementById("ddlChkList");
            var selectedItems = "";
            var arr = document.getElementById("chkLstItem").getElementsByTagName('input');
            var arrlbl = document.getElementById("chkLstItem").getElementsByTagName('label');
            var objLstId = document.getElementById('hidList');
            for (i = 0; i < arr.length; i++) {
                  checkbox = arr[i];
                  if (i == lstNo) {
                        if (ctrlType == 'anchor') {
                              if (!checkbox.checked) {
                                    checkbox.checked = true;
                              }
                              else {
                                    checkbox.checked = false;
                              }
                        }
                  }
                  if (checkbox.checked) {
                        if (selectedItems == "") {
                              selectedItems = arrlbl[i].innerText;
                        }
                        else {
                              selectedItems = selectedItems + "," + arrlbl[i].innerText;
                        }
                        noItemChecked = noItemChecked + 1;
                  }
            }
            ddlReport.title = selectedItems;
            var Text = ddlReport.options[ddlReport.selectedIndex].text;
            if (noItemChecked == 1)
                  ddlReport.options[ddlReport.selectedIndex].text = lstValue;
            else
                  ddlReport.options[ddlReport.selectedIndex].text = noItemChecked + " Items";
            document.getElementById('hidList').value = ddlReport.options[ddlReport.selectedIndex].text;
      }
      
      document.onclick = check;    
      function check(e) {
            var target = (e && e.target) || (event && event.srcElement);
            var obj = document.getElementById('divChkList');
            var obj1 = document.getElementById('ddlChkList');
            if (target.id != "alst" && !target.id.match("chkLstItem")) {
                  if (!(target == obj || target == obj1)) {
                        obj.style.display = 'none'
                  }
                  else if (target == obj || target == obj1) {
                        if (obj.style.display == 'block') {
                              obj.style.display = 'block';
                        }
                        else {
                              obj.style.display = 'none';
                              document.getElementById('ddlChkList').blur();
                        }
                  }
            }
      }
</script>


<table>
      <tr>
            <td valign="top" style="width: 165px">
                  <asp:PlaceHolder ID="phDDLCHK" runat="server"></asp:PlaceHolder>
            </td>
            <td valign="top">
                  <asp:Button ID="btn" runat="server" Text="Get Checked" OnClick="btn_Click" />
            </td>
            <td valign="top">
                  <asp:Label ID="lblSelectedItem" runat="server"></asp:Label>
            </td>
      </tr>
</table>
<asp:HiddenField ID="hidList" runat="server" />

</asp:Content>




Imports System.Data

Partial Class acb_test_2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load



        Dim ddl As New DropDownList()
        ddl.ID = "ddlChkList"
        Dim lstItem As New ListItem()
        ddl.Items.Insert(0, lstItem)
        ddl.Width = New Unit(155)
        'ddl.Attributes.Add("onmousedown", String.Format("showdivonClick('{0}')", divChkList.ClientID))
        Dim chkBxLst As New CheckBoxList()
        chkBxLst.ID = "chkLstItem"
        chkBxLst.Attributes.Add("onmouseover", "showdiv()")
        Dim dtListItem As DataTable = GetListItem()
        Dim rowNo As Integer = dtListItem.Rows.Count
        Dim lstValue As String = String.Empty
        Dim lstID As String = String.Empty
        For i As Integer = 0 To rowNo - 2
            lstValue = dtListItem.Rows(i)("Value").ToString()
            lstID = dtListItem.Rows(i)("ID").ToString()
            lstItem = New ListItem("<a href=""javascript:void(0)"" id=""alst"" style=""text-decoration:none;color:Black; "" onclick=""getSelectedItem(' " & lstValue & "','" & i & "','" & lstID & "','anchor');"">" & lstValue & "</a>", dtListItem.Rows(i)("ID").ToString())
            lstItem.Attributes.Add("onclick", "getSelectedItem('" & lstValue & "','" & i & "','" & lstID & "','listItem');")
            chkBxLst.Items.Add(lstItem)
        Next
        Dim div As New System.Web.UI.HtmlControls.HtmlGenericControl("div")
        div.ID = "divChkList"
        div.Controls.Add(chkBxLst)
        div.Style.Add("border", "black 1px solid")
        div.Style.Add("width", "160px")
        div.Style.Add("height", "180px")
        div.Style.Add("overflow", "AUTO")
        div.Style.Add("display", "none")
        'This is the addition, it had to be moved to be in scope to get the id
        ddl.Attributes.Add("onmousedown", String.Format("showdivonClick('{0}');", div.ClientID))
        phDDLCHK.Controls.Add(ddl)
        phDDLCHK.Controls.Add(div)
    End Sub

    Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn.Click


        Dim strSelectedItem As String = String.Empty
        Dim chk As CheckBoxList = DirectCast(phDDLCHK.FindControl("chkLstItem"), CheckBoxList)
        Dim ddl As DropDownList = DirectCast(Page.FindControl("ddlChkList"), DropDownList)

        For i As Integer = 0 To chk.Items.Count - 1
            If chk.Items(i).Selected Then
                If strSelectedItem.Length = 0 Then
                    strSelectedItem = chk.Items(i).Selected.ToString()
                Else
                    strSelectedItem = strSelectedItem & "," & chk.Items(i).Selected.ToString()

                End If
            End If
        Next
        ddl.Items.Clear()
        ddl.Items.Add(New ListItem(hidList.Value))
        lblSelectedItem.Text = strSelectedItem
    End Sub
    Public Function GetListItem() As DataTable
        Dim table As New DataTable()
        table.Columns.Add("ID", GetType(Integer))
        table.Columns.Add("Value", GetType(String))
        table.Rows.Add(1, "ListItem1")
        table.Rows.Add(2, "ListItem2")
        table.Rows.Add(3, "ListItem3")
        table.Rows.Add(4, "My ListItem Wraps also")
        table.Rows.Add(5, "My New ListItem5")
        table.Rows.Add(6, "ListItem6")
        table.Rows.Add(7, "ListItem7")
        table.Rows.Add(8, "ListItem8")
        Return table
    End Function

End Class

Open in new window

Author

Commented:
same error as above

Author

Commented:
when I changed "var objDLL = document.getElementById("divChkList");
to var objDLL = document.getElementById(objID);

error  : 'objID' is undefined

Commented:
Hey there, your function that you have in the code you just posted is this
      function showdivonClick() {
            var objDLL = document.getElementById("divChkList");
            if (objDLL.style.display == "block")
                  objDLL.style.display = "none";
            else 
                  objDLL.style.display = "block";
      }

Open in new window


But it should be this.... you need to have a parameter there
      function showdivonClick(   objID   ) {
            var objDLL = document.getElementById(  objID  );
            if (objDLL.style.display == "block")
                  objDLL.style.display = "none";
            else 
                  objDLL.style.display = "block";
      }

Open in new window

Author

Commented:
I tried that too. Same result. Have you tried it?
Commented:
I've tried it and when you posted your complete code sample it was flawed. You said you had tried it every which way. You didn't actually follow the suggestion and post your results (add an alert with the proper code) which makes it hard to step by step troubleshoot this with confidence that we are all on the same page.

I'll tell you what. I'll post my files that I tested and posted and showed you a screen shot of for you to try. Open a new website and put these files into it and run the debugger.

See if it can give you an idea of what you are doing wrong. I think its just one of those "head slap" moments.
AssignJSForID2.aspx.zip

Author

Commented:
Thanks. I did created a brand new project, just to play with this. It works now.  Thank you very much for samples.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.