locked
How do I get Checkboxlist values to the .aspx.vb file? RRS feed

  • Question

  • User-2123292311 posted

    <strike></strike>Essentially, what I'm trying to do is get a list of values out of a database and put them into a bunch of checkboxes.  When the user submits their selection of these checkboxes, I need to see what they've chosen.

    So I have no idea how many checkboxes I'll need, or what the values will be.  I will however be listing different categories.  I would like the final result to look something like this:


    <h1>category 1</h1>

    <input type="checkbox" name="cat1" value="avalue">

    <input type="checkbox" name="cat1" value="anothervalue">

    <input type="checkbox" name="cat1" value="somevalue">


    <h1>category 2</h1>

    <input type="checkbox" name="cat2" value="yetanothervalue">

    <input type="checkbox" name="cat2" value="valuestrikesback">


    and so forth.  I've experimented with the checkboxlist object as documented here:

    http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist.aspx

    However, I found this seemes to only work in the front end.  I need these values passed back to the backend so I can decide what to do with them.


    Might anyone have any suggestions for me? 

    --Thank you

    Wednesday, January 27, 2010 4:44 PM

Answers

  • User-577741185 posted

    This example returns an array of the items that were checked.

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default15.aspx.cs" Inherits="Default15" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" method="get" name="checkboxTest" runat="server">
        <h3>
            CheckBoxList Example
        </h3>
        Select items from the CheckBoxList.
        <br />
        <br />
        <asp:CheckBoxList ID="checkboxlist1" AutoPostBack="True" CellPadding="5" CellSpacing="5"
            RepeatColumns="2" RepeatDirection="Vertical" RepeatLayout="Flow" TextAlign="Right"
            runat="server">
            <asp:ListItem>Item 1</asp:ListItem>
            <asp:ListItem>Item 2</asp:ListItem>
            <asp:ListItem>Item 3</asp:ListItem>
            <asp:ListItem>Item 4</asp:ListItem>
            <asp:ListItem>Item 5</asp:ListItem>
            <asp:ListItem>Item 6</asp:ListItem>
        </asp:CheckBoxList>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <br />
        </form>
    </body>
    </html>
    

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Collections;
    
    public partial class Default15 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            ArrayList myArray = new ArrayList();
            foreach (ListItem item in checkboxlist1.Items)
            {
                if (item.Selected == true)
                {
                    myArray.Add(item);
                    Response.Write(item + "<br />");
                }
            }
        }
    }
    


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 27, 2010 6:53 PM
  • User-577741185 posted

    Oh, this might be important, I'm running vs 2003 on a .net1.1 version.

    Yeah! Try Imports System.Web.UI.WebControls.CheckBoxList

    also sorry, I didn't realize you posted this in VB.net

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 27, 2010 8:28 PM
  • User-577741185 posted

    Here's a sample to databind a checkboxlist:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCheckBoxList();
            }
        }    
        private void BindCheckBoxList()
        {
            SqlConnection conn;
            SqlCommand comm;
            SqlDataReader reader;
            string connectionString = ConfigurationManager.ConnectionStrings["yourConnectionString"].ConnectionString;
            conn = new SqlConnection(connectionString);
            comm = new SqlCommand("SELECT catagory, catagoryID FROM Catagories", conn);
            conn.Open();
            reader = comm.ExecuteReader();
            CheckBoxList1.DataSource = reader;
            CheckBoxList1.DataTextField = "catagory";
            CheckBoxList1.DataValueField="catagoryID";
            CheckBoxList1.DataBind();
            reader.Close();
            conn.Close();
        }


    Make sure you have the following namespaces:
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 28, 2010 5:32 PM
  • User-2123292311 posted


    All right.  I feel I've almost got this working.  I tried to translate the best I could, but some things are simply innately different.  When the page loads, the checklist DOES get populated, which is nice.  However, I seem to have lost the ability to do anything with it once it gets checked. 

    Here is my aspx code:

    <form id="form1" method="post" name="checkboxTest" runat="server">
    
     <h3> CheckBoxList Example </h3>
    
     Select items from the CheckBoxList.
    
     <br /><br />
    			
     <asp:CheckBoxList id="checkboxlist1" 
    	 AutoPostBack="True"
    	 CellPadding="5"
    	  CellSpacing="5"
    	  RepeatColumns="2"
    	  RepeatDirection="Vertical"
    	  RepeatLayout="Flow"
    	  TextAlign="Right"				   
    	  runat="server">
     </asp:CheckBoxList>
     <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />  
     <br />
     </form>


    And here is my vb:

    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Text
    Imports System.Text.RegularExpressions
    imports System
    Imports System.Web.UI.WebControls.CheckBoxList
    Imports System.Web  
    Imports System.Web.UI  
    Imports System.Web.UI.WebControls  
    Imports System.Collections  
    Imports System.Configuration
    
    Public Class test
        Inherits System.Web.UI.Page
        Protected WithEvents HyperLink1 As System.Web.UI.WebControls.HyperLink
        Protected WithEvents checkboxlist1 As System.Web.UI.WebControls.CheckBoxList
        Protected WithEvents Button1 As System.Web.UI.WebControls.Button
        Protected WithEvents form1 As System.Web.UI.HtmlControls.HtmlForm
    
    
    
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Put user code to initialize the page here
            bindCheckbox()
        End Sub
    
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim myArray As ArrayList = New ArrayList
            For Each item As ListItem In checkboxlist1.Items
                If item.Selected = True Then
                    myArray.Add(item)
                    Response.Write(item)
                    Response.Write("<br />")
                End If
            Next
        End Sub
    	
    	private sub bindCheckbox() 
    		'database vars
            Dim mySqlDataReader As SqlDataReader
            Dim Info As SqlConnection
            Dim mySqlCommand As SqlCommand
            Dim query As String
            
            Try
                myInfo = MainMod.DataConnection
                query = "SELECT productName FROM products ORDER BY partop ASC"
                mySqlCommand = New SqlCommand(query, Info)
                mySqlDataReader = mySqlCommand.ExecuteReader
            Catch ex As Exception
                Response.Write("ppn-failed to execute query " & query)
            End Try
    		
    		mySqlDataReader.Read()
    		CheckBoxList1.DataSource = mySqlDataReader
            checkboxlist1.DataTextField = "productName"
    		CheckBoxList1.DataBind()
    	end sub
    
    
    


    Also note, with the  AutoPostBack="True" in the aspx portion, as soon as I click a checkbox the check goes away.  I would assume at this point Button1_Click would tell me what I clicked on, but it doesn't.  If it turn it to "False," it waits till I click the submit button, but still doesn't return anything.

    Thank you so much for all the suggestions and ideas so far!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 28, 2010 6:21 PM
  • User-577741185 posted

    You need to put the bindCheckBox sub inside the if not is postback


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            BindCheckBoxList()
        End If
    End Sub

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 28, 2010 6:47 PM

All replies

  • User-577741185 posted

    You can use CheckBoxLists in the backend

    protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedValue1 = CheckBoxList1.SelectedValue.ToString();
            string selectedValue2 = CheckBoxList2.SelectedValue.ToString();
        }

    Now you can do whatever you want with them

    Wednesday, January 27, 2010 5:17 PM
  • User1282917655 posted

    Is that what you mean ?

     

            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
                <asp:ListItem Value="1">item 1</asp:ListItem>
                <asp:ListItem Value="2">Item 2</asp:ListItem>
                <asp:ListItem Value="3">Item 3</asp:ListItem>
            </asp:RadioButtonList>
     
     


     

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Response.Write(Me.RadioButtonList1.SelectedValue)
        End Sub


     

    Wednesday, January 27, 2010 5:21 PM
  • User-2123292311 posted

    I'm sorry my original post did not include a specifc code example.  This is the code in my aspx file:


    <form id="form1" method="get" name="checkboxTest" runat="server">
    
      <h3> CheckBoxList Example </h3>
    
      Select items from the CheckBoxList.
    
      <br /><br />
    
      <asp:CheckBoxList id="checkboxlist1" 
    	   AutoPostBack="True"
    	   CellPadding="5"
    	   CellSpacing="5"
    	   RepeatColumns="2"
    	   RepeatDirection="Vertical"
    	   RepeatLayout="Flow"
    	   TextAlign="Right"				   
    	   runat="server">
    
    	 <asp:ListItem>Item 1</asp:ListItem>
    	 <asp:ListItem>Item 2</asp:ListItem>
    	 <asp:ListItem>Item 3</asp:ListItem>
    	 <asp:ListItem>Item 4</asp:ListItem>
    	 <asp:ListItem>Item 5</asp:ListItem>
    	 <asp:ListItem>Item 6</asp:ListItem>
    
      </asp:CheckBoxList>
     
    
      <br />
      <input type="submit">
      <br />	  
    
    </form>



    Please note that unlike the example I link to in my original post, I do not have a sub in my aspx file called  Check_clicked.

    So my question to you is, what should I put on my backend to, just for this example, print out the variables chosen in the front end?


    --Thank you

    Wednesday, January 27, 2010 5:45 PM
  • User-2123292311 posted

    So to clarify,  I should not get a string returned, but instead an array.  An array of strings. 

    Wednesday, January 27, 2010 5:59 PM
  • User-577741185 posted

    This example returns an array of the items that were checked.

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default15.aspx.cs" Inherits="Default15" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" method="get" name="checkboxTest" runat="server">
        <h3>
            CheckBoxList Example
        </h3>
        Select items from the CheckBoxList.
        <br />
        <br />
        <asp:CheckBoxList ID="checkboxlist1" AutoPostBack="True" CellPadding="5" CellSpacing="5"
            RepeatColumns="2" RepeatDirection="Vertical" RepeatLayout="Flow" TextAlign="Right"
            runat="server">
            <asp:ListItem>Item 1</asp:ListItem>
            <asp:ListItem>Item 2</asp:ListItem>
            <asp:ListItem>Item 3</asp:ListItem>
            <asp:ListItem>Item 4</asp:ListItem>
            <asp:ListItem>Item 5</asp:ListItem>
            <asp:ListItem>Item 6</asp:ListItem>
        </asp:CheckBoxList>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />
        <br />
        </form>
    </body>
    </html>
    

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Collections;
    
    public partial class Default15 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            ArrayList myArray = new ArrayList();
            foreach (ListItem item in checkboxlist1.Items)
            {
                if (item.Selected == true)
                {
                    myArray.Add(item);
                    Response.Write(item + "<br />");
                }
            }
        }
    }
    


    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 27, 2010 6:53 PM
  • User-2123292311 posted

    I've been trying to translate that c# into vb, sorry I'm not very proficient in c#.  I'm having some trouble, this is what I've got so far:


    imports System
    Imports System.Web  
    Imports System.Web.UI  
    Imports System.Web.UI.WebControls  
    Imports System.Collections  


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs 
            Dim myArray As ArrayList = New ArrayList
            For Each item As ListItem In checkboxlist1.Items
                If item.Selected = True Then
                    myArray.Add(item)
                    Response.Write(item & "<br />")
                End If
            Next
        End Sub


    and I made the change to the aspx file as well:

    <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />


    However, vs underlines checkboxlist1.Items in my for each loop saying "checkboxlist1 is not declared"


    What am I missing?

    Wednesday, January 27, 2010 8:10 PM
  • User-577741185 posted

    However, vs underlines checkboxlist1.Items in my for each loop saying "checkboxlist1 is not declared"

    Make sure your CheckBoxList control is name "checkboxlist1".

    btw, you can always use this to convert code. http://www.developerfusion.com/tools/convert/csharp-to-vb/

    Wednesday, January 27, 2010 8:15 PM
  • User-2123292311 posted

    Make sure your CheckBoxList control is name "checkboxlist1".


    it is.  Do I not need to declare it in the vb side?  Its only declared in the aspx side. 


    btw, you can always use this to convert code. http://www.developerfusion.com/tools/convert/csharp-to-vb/


    I did, it kept telling me my statement was incomplete :(

    Which is quite odd I mean as far as I could tell it was solid. 


    Oh, this might be important, I'm running vs 2003 on a .net1.1 version. 


    Thanks for the ideas so far!

    Wednesday, January 27, 2010 8:21 PM
  • User-577741185 posted

    Oh, this might be important, I'm running vs 2003 on a .net1.1 version.

    Yeah! Try Imports System.Web.UI.WebControls.CheckBoxList

    also sorry, I didn't realize you posted this in VB.net

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, January 27, 2010 8:28 PM
  • User-2123292311 posted

    Alright, with your latest suggestion I was able to get that code working.  Huray!


    However.. I've been trying to reproduce the results but have the checkboxes be automatically generated.  This is giving me some trouble.  Now as I said in my original post, I'm trying to get information out of a database and display it as options in a check list.  Because I'm dealing with connecting to a mssql database I'm trying to write my function in the back end. 

    There are a wealth of problems with that however.

    First off, the code rivdiv suggested had vs automatically generate this code immediately under my public class statement

    Inherits System.Web.UI.Page
    Protected WithEvents HyperLink1 As System.Web.UI.WebControls.HyperLink
    Protected WithEvents checkboxlist1 As System.Web.UI.WebControls.CheckBoxList
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents form1 As System.Web.UI.HtmlControls.HtmlForm


    which I actually didn't notice until just a little bit ago.

    So I have this backend function that gets the information I want to turn into a checkboxlist and prints it out like so:

    Response.Write("<form id=""form1"" method=""get"" name=""checkboxTest"" runat=""server"">")
            Response.Write("<h3> CheckBoxList Example </h3>")
            Response.Write("Select items from the CheckBoxList.")
            Response.Write("<br /><br />")
            Response.Write("<asp:CheckBoxList id=""checkboxlist1""")
            Response.Write("AutoPostBack=""True""")
            Response.Write("CellPadding=""5""")
            Response.Write("CellSpacing=""5""")
            Response.Write("RepeatColumns=""2""")
            Response.Write("RepeatDirection=""Vertical""")
            Response.Write("RepeatLayout=""Flow""")
            Response.Write("TextAlign=""Right""")
            Response.Write("runat=""server"">")
    
            While SqlDataReader.Read()
                product= eoSqlDataReader("product")
                Response.Write("<asp:ListItem>" & product & "</asp:ListItem>")
            End While
    
            Response.Write(" </asp:CheckBoxList>")
            Response.Write("<br />		<asp:Button ID=""Button1"" runat=""server"" Text=""Submit"" OnClick=""Button1_Click"" /> 	<br />	   </form>")


    but of course this printed everything out literally.  and was of no use.

    So now that I have successfully figured out how to get information from checkboxlists in the backend, how do I dynamically generate the checkboxlists?



    Thursday, January 28, 2010 5:15 PM
  • User-577741185 posted

    Here's a sample to databind a checkboxlist:

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCheckBoxList();
            }
        }    
        private void BindCheckBoxList()
        {
            SqlConnection conn;
            SqlCommand comm;
            SqlDataReader reader;
            string connectionString = ConfigurationManager.ConnectionStrings["yourConnectionString"].ConnectionString;
            conn = new SqlConnection(connectionString);
            comm = new SqlCommand("SELECT catagory, catagoryID FROM Catagories", conn);
            conn.Open();
            reader = comm.ExecuteReader();
            CheckBoxList1.DataSource = reader;
            CheckBoxList1.DataTextField = "catagory";
            CheckBoxList1.DataValueField="catagoryID";
            CheckBoxList1.DataBind();
            reader.Close();
            conn.Close();
        }


    Make sure you have the following namespaces:
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 28, 2010 5:32 PM
  • User-2123292311 posted


    All right.  I feel I've almost got this working.  I tried to translate the best I could, but some things are simply innately different.  When the page loads, the checklist DOES get populated, which is nice.  However, I seem to have lost the ability to do anything with it once it gets checked. 

    Here is my aspx code:

    <form id="form1" method="post" name="checkboxTest" runat="server">
    
     <h3> CheckBoxList Example </h3>
    
     Select items from the CheckBoxList.
    
     <br /><br />
    			
     <asp:CheckBoxList id="checkboxlist1" 
    	 AutoPostBack="True"
    	 CellPadding="5"
    	  CellSpacing="5"
    	  RepeatColumns="2"
    	  RepeatDirection="Vertical"
    	  RepeatLayout="Flow"
    	  TextAlign="Right"				   
    	  runat="server">
     </asp:CheckBoxList>
     <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" />  
     <br />
     </form>


    And here is my vb:

    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.Text
    Imports System.Text.RegularExpressions
    imports System
    Imports System.Web.UI.WebControls.CheckBoxList
    Imports System.Web  
    Imports System.Web.UI  
    Imports System.Web.UI.WebControls  
    Imports System.Collections  
    Imports System.Configuration
    
    Public Class test
        Inherits System.Web.UI.Page
        Protected WithEvents HyperLink1 As System.Web.UI.WebControls.HyperLink
        Protected WithEvents checkboxlist1 As System.Web.UI.WebControls.CheckBoxList
        Protected WithEvents Button1 As System.Web.UI.WebControls.Button
        Protected WithEvents form1 As System.Web.UI.HtmlControls.HtmlForm
    
    
    
        Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Put user code to initialize the page here
            bindCheckbox()
        End Sub
    
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
            Dim myArray As ArrayList = New ArrayList
            For Each item As ListItem In checkboxlist1.Items
                If item.Selected = True Then
                    myArray.Add(item)
                    Response.Write(item)
                    Response.Write("<br />")
                End If
            Next
        End Sub
    	
    	private sub bindCheckbox() 
    		'database vars
            Dim mySqlDataReader As SqlDataReader
            Dim Info As SqlConnection
            Dim mySqlCommand As SqlCommand
            Dim query As String
            
            Try
                myInfo = MainMod.DataConnection
                query = "SELECT productName FROM products ORDER BY partop ASC"
                mySqlCommand = New SqlCommand(query, Info)
                mySqlDataReader = mySqlCommand.ExecuteReader
            Catch ex As Exception
                Response.Write("ppn-failed to execute query " & query)
            End Try
    		
    		mySqlDataReader.Read()
    		CheckBoxList1.DataSource = mySqlDataReader
            checkboxlist1.DataTextField = "productName"
    		CheckBoxList1.DataBind()
    	end sub
    
    
    


    Also note, with the  AutoPostBack="True" in the aspx portion, as soon as I click a checkbox the check goes away.  I would assume at this point Button1_Click would tell me what I clicked on, but it doesn't.  If it turn it to "False," it waits till I click the submit button, but still doesn't return anything.

    Thank you so much for all the suggestions and ideas so far!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 28, 2010 6:21 PM
  • User-577741185 posted

    You need to put the bindCheckBox sub inside the if not is postback


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            BindCheckBoxList()
        End If
    End Sub

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, January 28, 2010 6:47 PM
  • User-2123292311 posted

    Excellent yes thank you that worked well! 


    I'm going to go ahead and mark this post as answered!



    Sunday, January 31, 2010 9:12 AM