passing checkboxlist selected items as a concatenated string - asp.net

I am trying to pass the selected items from a checkboxlist in asp.net (vs 2005/.net 2.0) as a concatenated string.
Currently my .aspx is
<asp:CheckBoxList id="checkbox1" AutoPostBack="False" AppendDataBoundItems="true" CellPadding="5" CellSpacing="5" RepeatColumns="1" RepeatDirection="Vertical" RepeatLayout="Flow" TextAlign="Right" runat="server">
<asp:ListItem Value="1">Carrots</asp:ListItem>
<asp:ListItem Value="2">Lettuce</asp:ListItem>
<asp:ListItem Value="3">Olives</asp:ListItem>
<asp:ListItem Value="4">Onions</asp:ListItem>
<asp:ListItem Value="5">Tomato</asp:ListItem>
<asp:ListItem Value="6">Pickles</asp:ListItem>
</asp:CheckBoxList>
And the .aspx.vb is (inside the Protected Sub for submit)
For Each li As ListItem In checkbox1.Items
If li.Selected = True Then
checkbox1.Text = checkbox1.Text + "," + li.Text
End If
Next
Which is written to the db via
checkbox1.Text = dv(0)("Salad").ToString()
When I select and save, I am currently getting an error
Server Error in '/' Application.
'checkbox1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Any thoughts on how to concatenate the selected checkbox items
For example, if some selects Carrots, Lettuce, and Tomato;
checkbox1 = 1,2,5

I don't think you are assigning to a variable like you describe you are returning.
string list = "";
For Each li As ListItem In chkQ4.Items
If li.Selected = True Then
list = list + "," + li.Text
End If
Next
is how you should write the line above.
In C# using linq, I would write
var list = checkbox1.Items
.Cast<ListItem>()
.Where(item => item.Selected == true)
.Select(item => item.Value);
var result = string.Join(",",list);
which I believe is the following in VB
Dim list = checkbox1.Items.Cast(Of ListItem)().Where(Function(item) item.Selected = True).[Select](Function(item) item.Value)
Dim result = String.Join(",", list.ToArray())

This is a little example
Markup:
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="1">Carrots</asp:ListItem>
<asp:ListItem Value="2">Apples</asp:ListItem>
<asp:ListItem Value="3">Lettuce</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Concatenate" /><br />
<asp:Button ID="Button2" runat="server" Text="Save" />
Codebehind:
Private Sub SaveItems(ByVal strItems As String)
Dim cn As New SqlConnection("user id=sa;password=abcd;database=BD_Test;server=SERVNAME")
Dim cmd As New SqlCommand("Insert into CheckItems values (#ItemId)", cn)
Dim cmdPar As New SqlParameter("#ItemId", SqlDbType.Char, 1)
If strItems.Split(",").Length > 0 Then
cmd.Parameters.Add(cmdPar)
Using cn
cn.Open()
Using cmd
''Split the existing selected values, store it in an array
''and iterate to get each element of it to save it in the DB
For Each strItem As String In strItems.Split(",")
cmd.Parameters("#ItemId").Value = strItem
cmd.ExecuteNonQuery()
Next
End Using
Me.Literal1.Text = "Items saved"
End Using
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Literal1.Text = ""
For Each l As ListItem In Me.CheckBoxList1.Items
''Concatenate keeping the order of the items in your CheckboxList
If l.Selected Then
Me.Literal1.Text = Me.Literal1.Text & l.Value & ","
End If
Next
''Remove the final "," in case its at the end of the string
''to avoid db issues and selected items issues
If Right(Me.Literal1.Text, 1) = "," Then
Me.Literal1.Text = Left(Me.Literal1.Text, Me.Literal1.Text.Length - 1)
End If
''You can also save the items directly after concatenating
''Me.SaveItems(Me.Literal1.Text)
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.SaveItems(Me.Literal1.Text)
End Sub
The expected result is to have the selected values of the items on the page literal:
1,3
Hope this helps.

Related

Button Stops Functioning when Trying to Assign Session Variable

I am trying to retain a list of strings after a button press and have been using session variables. This is a snippet of the code:
.aspx page
<asp:Panel runat="server" ID="pnlAdd" >
<asp:DropDownList runat="server" ID="ddlOrder" >
<asp:ListItem Value="-1">Select an Order Type</asp:ListItem>
<asp:ListItem Value="1">hey there</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList runat="server" ID="ddlOrderStatus" >
<asp:ListItem Value="-1">Select an Order Status</asp:ListItem>
<asp:ListItem Value="1">another option</asp:ListItem>
</asp:DropDownList>
</asp:Panel>
<br />
<asp:Button runat="server" ID="btnAdd" Text="Add" />
.vb page
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim list As New List(Of String)
list = Session("flist")
list.Add(ddlOrder.SelectedItem.Text + " " + ddlOrderStatus.SelectedItem.Text)
Session("flist") = list
For i As Integer = 0 To 10
MsgBox(i.ToString + " " + list(i))
Next
MsgBox("Here")
End Sub
At the point that I assign the Session variable to list with list = Session("flist"), nothing will happen on the button click. If I remove that line, the rest of the button fires. Am I using the Session variable incorrectly? How can I achieve this correctly?
The list (of String) cannot be nothing before you are going to add elements into this list, So, change your code as follows:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim list As New List(Of String)
Dim objList As Object = Session.Item("flist")
If objList IsNot Nothing AndAlso TypeOf (objList) Is List(Of String) Then
list = CType(objList, List(Of String))
End If
list.Add(ddlOrder.SelectedItem.Text + " " + ddlOrderStatus.SelectedItem.Text)
Session("flist") = list
For i As Integer = 0 To list.Count - 1
MsgBox(i.ToString + " " + list(i))
Next
MsgBox("Here on end")
End Sub

how to get all values of selected checkbox in vb.net and set it on string list

I need to get selected items on checkbox and set as string format like (value1,value2,value3) from the checkbox i selected
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim CheckRow As CheckBox = (TryCast(row.Cells(1).FindControl("chckSelector"), CheckBox))
If CheckRow.Checked Then
Dim scode As String = TryCast(row.Cells(2).FindControl("lblsstorecode"), Label).Text
lbltest.Text = 'this i want to get the value like this (value1,value2,value3) from checkbox that i selected
End If
End If
Next
Depending on why you are using the GridView control, you might me able to accomplish this easier by using a CheckBoxList instead. In Asp.net what you describe is accomplished very easily with a CheckBoxList as follows:
In .aspx:
<asp:CheckBoxList ID="Itemlst" runat="server" RepeatColumns="1">
<asp:ListItem Value="">Item 1</asp:ListItem>
<asp:ListItem Value="">Item 2</asp:ListItem>
<asp:ListItem Value="">Item 3</asp:ListItem>
</asp:CheckBoxList>
</br>
<asp:Button ID="Button1" runat="server" Text="Button" />
</br>
<asp:TextBox ID="TextBox1" runat="server" Width="400"></asp:TextBox>
Then in the code behind:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim selected = New List(Of ListItem)
Dim itemcount As Integer
Dim csvlist As String = ""
For Each item As ListItem In Itemlst.Items
If item.Selected Then selected.Add(item)
Next
itemcount = selected.Count
For i = 0 To itemcount - 1
csvlist = csvlist & selected(i).ToString & ","
Next
csvlist = Mid(csvlist, 1, Len(csvlist) - 1)
TextBox1.Text = csvlist
End Sub
The Windows Forms CheckedListBox would probably work similar if you are developing a desktop application.

i want to add dynamic controls to panel by button click which should not override existing dynamically created controls

This is the Design:::
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim i As Integer = 0
Dim j As Integer = 0
l1.Text = l2.Text
l2.Text = Val(l2.Text) + 10
i = Val(l1.Text)
j = Val(l2.Text)
MsgBox(i & " " & j)
While (i < j)
Dim b As Button = New Button()
b.ID = "b" + i.ToString()
b.Text = b.ID
Panel1.Controls.Add(b)
i = i + 1
End While
End Sub
This contains a button on click it should create 10 unique buttons..
i want to append all created buttons with existing buttons..
but the program is overriding instead of adding controls to the panel
help me.
I just tried this code. It doesn't override anything. It add the buttons to the very start of the page. If you want the buttons to appear after the button 'button 2' and labels then you should place the Panel, then it should be something like this
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
And if you want button to get added up along side the existing button and labels then instead of Panel either just use a place holder, or add style 'display:inline' to the Panel.
I think you want to add 10 dynamic controls on every button click. The problem you are facing right know is that on first click it adds 10 button controls, and on subsequent clicks it overrides the previous controls. Dynamic controls are created every time the page is requested so you have to create them on every request.
I write the following code to solve your query and it works:
// Aspx code
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
// Code BEhind
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim i As Integer = 0
Dim j As Integer = 0
l1.Text = l2.Text
l2.Text = Val(l2.Text) + 10
i = Val(l1.Text)
j = Val(l2.Text)
MsgBox(i & " " & j)
Dim lst As List(Of Integer) = New List(Of Integer) 'Create a list of integer type
lst.Add(i) 'Save value of i
lst.Add(j)
If Not Session("id_0") Is Nothing Then ' Will Check session for First Click exist or not
For k As Integer = 0 To DirectCast(Session("click"), Integer)
Dim mylst As List(Of Integer) = New List(Of Integer)
mylst = DirectCast(Session("id_" & k), List(Of Integer)) ' Assign Session Value to List
If Not mylst Is Nothing Then
WriteControls(mylst(0), mylst(1)) ' Call the function
End If
Next
End If
Session("id_" & DirectCast(Session("click"), Integer)) = lst ' Saves the entire list in Session
WriteControls(i, j) ' Function Call
End Sub
Private Sub WriteControls(i As Integer, j As Integer) ' Function to write button control
While (i < j)
Dim b As Button = New Button()
b.ID = "b" + i.ToString()
b.Text = b.ID
b.ViewStateMode = UI.ViewStateMode.Enabled
Panel1.Controls.Add(b)
i = i + 1
End While
Session("click") = DirectCast(Session("click"), Integer) + 1
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Session("click") = 0 ' Stores the no. of Clicks of the button
End If
End Sub
' Output
' If I press three times button then there will be 30 buttons
b0 b1 b2 b3 b4 ............................................... b29
20 30

How do I keep Selected ListItem from ignoring other ListItems?

When I run code the below, the If statement never resolves to 'True'. It always shows 'Assm' as the SelectedItem, even if I check all the checkboxes.
So how do I allow 'Assm' to be checked by default AND have the code-behind see that the other checkboxes are checked?
<asp:CheckBoxList ID="qualityChecks" runat="server" RepeatDirection="Horizontal" TabIndex="8">
<asp:ListItem Text="Assm" Selected="True"></asp:ListItem>
<asp:ListItem Text="Qual"></asp:ListItem>
<asp:ListItem Text="PMgr"></asp:ListItem>
<asp:ListItem Text="Plant"></asp:ListItem>
</asp:CheckBoxList>
If qualityChecks.SelectedItem.Text = "Qual" Then
'Some Code
End If
SelectedItem of a CheckBoxList works that way.
What you want to do is iterate through the ListItems and see if they are Checked.
For each li as ListItem in qualitychecks.items
if li.checked and li.text = "Qual" then
'some code
end if
next
Try creating an empty CheckListBox:
<asp:CheckBoxList ID="qualityChecks" runat="server" RepeatDirection="Horizontal" TabIndex="8">
</asp:CheckBoxList>
and than adding the ListItems on Page_Load
Protected Sub Page_Load(sender As Object, e As EventArgs)
Dim l1 As New ListItem()
Dim l2 As New ListItem()
Dim l3 As New ListItem()
Dim l4 As New ListItem()
l1.Text = "Assm"
l2.Text = "Qual"
l3.Text = "PMgr"
l4.Text = "Plant"
If Not Page.IsPostBack Then
l1.Selected = True
qualityChecks.Items.Add(l1)
qualityChecks.Items.Add(l2)
qualityChecks.Items.Add(l3)
qualityChecks.Items.Add(l4)
End If
End Sub
Try:
If qualityChecks.SelectedValue = "Qual" Then
'Some Code
End If
As you have specified no value for the list items, they take the value of the Text

Checkboxes in usercontrol won't check although they say they are

I have a simple usercontrol, with a datalist, and checkboxes inside.
<asp:DataList ID="DataListDroits" runat="server" DataKeyField="droit_id" DataSourceID="SqlDroits">
<ItemTemplate>
<asp:HiddenField ID="HiddenFieldDroitID" runat="server" Value='<%# Eval("droit_id") %>' />
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' />
</ItemTemplate>
</asp:DataList>
I check them using code behind in the usercontrol :
Public Sub CheckRole(ByVal role As Integer)
For Each dliOrganisme As DataListItem In Me.DataListOrganismes.Items
Dim DataListDroits As DataList = dliOrganisme.FindControl("DataListDroits")
If DataListDroits IsNot Nothing Then
For Each dliDroit As DataListItem In DataListDroits.Items
If role = CInt(CType(dliDroit.FindControl("HiddenFieldDroitID"), HiddenField).Value) Then
Dim CheckBoxDroit As CheckBox = dliDroit.FindControl("CheckBoxDroit")
CheckBoxDroit.Checked = True
End If
Next ' DataListDroits
End If
Next ' DataListItem
End Sub
And in the page_load of the calling webform :
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
Dim rolesCoches As New List(Of Integer)
Dim cmdRoles As New SqlCommand("SELECT droit_id FROM o_droit_rubrique WHERE rubrique_id = #rubrique", conn)
cmdRoles.Parameters.AddWithValue("rubrique", Request.QueryString("rid"))
Dim rdrRoles As SqlDataReader = cmdRoles.ExecuteReader
While rdrRoles.Read
CheckBoxesRoles1.CheckRole(rdrRoles("droit_id"))
End While
rdrRoles.Close()
... and yet, they are not checked.
But if I do this :
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
If CheckBoxesRoles1 IsNot Nothing Then
For Each role As Integer In CheckBoxesRoles1.CheckedRoles
Response.Write("role : " & role & "<br>")
Next
End If
End Sub
I tells me they are...
I'm going mad here ! Why does it tells me they are checked while they obviously are not ?
Well... for one thing, you aren't checking if your checkboxes are checked, all you're doing is outputting the value of "role". What exactly are you expecting here?
Two suggestions:
1) Set the Checked property of your CheckBox in the aspx like so:
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' Checked='<%# (Eval("droit_id") > 0).ToString()' />
2) Set the property in OnItemDataBound in code-behind
One of two things is happening: Either the code you expect to be executing is not really executing (ie, is your if block ever true? Is the control not being found? Try a breakpoint), OR you are doing it at the wrong time -- after the page has already been rendered.

Resources