Select multiple value in DropDownList - asp.net

I have a dropdownlist (SingleSelection) which retrieve the data from sql database, I want to change it to MultiSelection (select multi value), following is my code.
ASP.NET
<asp:DropDownList ID="DrpGroup" runat="server" Width="250px" AutoPostBack="True">
</asp:DropDownList>
VB
Protected Sub DrpGroup_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DrpGroup.SelectedIndexChanged
If (DrpGroup.SelectedValue.ToString.Trim.ToUpper <> "PLEASE SELECT...") Then
Dim cnt_value As Integer = TDES.FindKey("Select Count(*) from dbo.VU_CUSTOMERBYGROUP WHERE upper(ltrim(rtrim(GROUP_NAME)))='" & DrpGroup.SelectedValue.ToString.Trim.ToUpper & "'")
lblNumberCount.Visible = True
lblNumberCount.Text = DrpGroup.SelectedValue.ToString.Trim.ToUpper & " has " & CStr(cnt_value) & " member(s). <br /> The cost for this SMS broadcast will be xxx" & CStr(cnt_value * 0.5)
End If
If (DrpGroup.SelectedValue.ToString.Trim.ToUpper = "PLEASE SELECT...") Then
lblNumberCount.Visible = False
End If
End Sub
Your efforts would be appreciated.

Use ListBox instead of DropDownList
<asp:ListBox runat="server" ID="multiSelect" SelectionMode="multiple" >
<asp:ListItem Text="option1" Value="option1"></asp:ListItem>
<asp:ListItem Text="option2" Value="option2"></asp:ListItem>
<asp:ListItem Text="option3" Value="option3"></asp:ListItem>
</asp:ListBox>

Related

Upload files in vb.net

I have a code in vb.net (as shown below) in which it ask to upload a file after the selection of yes button. On checking No button, it doesn't ask us to upload a file as shown below in the images.
************************************************VB Code******************************************************
Protected Sub rblOrgChart_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rblOrgChart.SelectedIndexChanged
ruOrgChart.Visible = False
hlOrgChart.Visible = False
' btnOrgChart.Visible = rblOrgChart.SelectedValue And bolHasWritePermission
hlOrgChart.Visible = rblOrgChart.SelectedValue
If CBool(rblOrgChart.SelectedValue) Then
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
Else
' If Me.lblOrgChartMissing2.Visible Then Me.lblOrgChartMissing2.Visible = False
End If
End Sub
The code inside the method btnOrgChart_Click is:
Protected Sub btnOrgChart_Click(sender As Object, e As System.EventArgs) Handles btnOrgChart.Click
Try
'If ruOrgChart.InvalidFiles.Count > 0 Then
' lblOrgChartNotPDF.Visible = True
'Else
' lblOrgChartNotPDF.Visible = False
'End If
'------------------------------------------------------------------
' Q07. HAS WRITTEN ORG. CHART [IAPData..tblReadinessProfile_Question ID=9 ]
'------------------------------------------------------------------
If (rblOrgChart.SelectedValue = 1 And ruOrgChart.UploadedFiles.Count > 0) Then
hlOrgChart.Visible = True
'' ''======' BEGIN NEW CODE --- to upload file to virtual directory
Dim sufile As Telerik.Web.UI.UploadedFile = Nothing
For Each sufile In Me.ruOrgChart.UploadedFiles
' for now upload files on webserver
'If AppSettings.Item("Environment") <> "Prod" Then
remoteName = Request.PhysicalApplicationPath
'Else
'remoteName = AppSettings.Item("UploadRootPath").ToString.Trim()
'End If
Dim strPhysicalFilePath As String = remoteName & AppSettings.Item("FileUploadRootPath").ToString & "\" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "\" & dtOrg.Rows(0).Item("OrgCode").ToString & "\"
CreateFileUploaderLink(remoteName)
If Not Directory.Exists(strPhysicalFilePath) Then
Directory.CreateDirectory(strPhysicalFilePath)
End If
hlOrgChart.NavigateUrl = AppSettings.Item("FileUploadRootPath").ToString & "/" & dtLicensee.Rows(0).Item("UniqueIdentifier").ToString & "/" & dtOrg.Rows(0).Item("OrgCode").ToString & "/" & ruOrgChart.UploadedFiles(0).GetName()
dalClientProfile.SaveFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART, ruOrgChart.UploadedFiles(0).GetName(), strPhysicalFilePath, True)
hlOrgChart.Text = ruOrgChart.UploadedFiles(0).GetName()
Dim NewFileName As String
NewFileName = sufile.GetName()
'If File.Exists(strPhysicalFilePath & NewFileName) Then
' Dim script As String = "alert('" + Me.GetLocalResourceObject("err.fileuploaded.text") + "');"
' ScriptManager.RegisterStartupScript(ruOrgChart, ruOrgChart.GetType(), "clientscript", script, True)
' Exit Sub
'End If
sufile.SaveAs(strPhysicalFilePath & NewFileName, True)
' Cancel the connection
RemoveFileUploaderLink(remoteName)
Next
End If
Catch ex As Exception
Dim oErr As New ErrorLog(ex, "Error in btnOrgChart_Click")
Response.Redirect("~/Error/ErrorPage.aspx?type=Err&ui=" & Request.QueryString("ui"), True)
Exit Sub
End Try
End Sub
**********************************************Images*******************************************************
As shown above in the images, on selection of yes it ask us to upload a file.
By default, it always remains No as the value of HasOrgChart is always 0.
rblOrgChart.SelectedValue = IIf(CBool(dtOrg.Rows(0).Item("HasOrgChart")), 1, 0)
******************************************************HTML*************************************************
The .aspx code belonging to the above images and to the above vb codes are:
<div class="grid-c2">
<div>
<asp:UpdatePanel runat="server" ID="Updatepanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>
<ContentTemplate>
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
<div>
<br />
<telerik:RadAsyncUpload ID="ruOrgChart" runat="server" AutoPostBack="true"
HideFileInput="True"
AllowedFileExtensions=".pdf"
OnClientValidationFailed="validationFailed"
onclientfileuploaded="ruOrgChart_Fileuploaded"
MaxFileInputsCount="1"
InitialFileInputsCount="1"
MaxFileSize="5000000"
/>
<div class="fileLink">
<asp:HyperLink runat="server" ID="hlOrgChart" Target="_blank" Visible="false"
Text=""></asp:HyperLink>
</div>
</div>
<br />
<div style="display:none">
<asp:linkButton ID="btnOrgChart" CssClass="btnUpload" runat="server" Text="" />
</div>
<br />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
I am wondering what changes do I need to make in the vb.net and .aspx codes so that instead of Yes and No radio button, there is only select button which ask us directly to upload a file with no yes/no options.
You already have a select button on your form. Why not bypass the Yes/No and just use that?
You should have a Sub btnOrgChart_Click code somewhere. Your variable names don't match with your intended actions, but I think that under the Click code, you might want this somewhere:
ruOrgChart.Visible = True
Dim dtFile As DataTable
dtFile = dalClientProfile.GetFileUpload(CInt(Session("OrgID")), CInt(Session("LicenseeID")), enumFileTypeUpload.ORG_CHART)
If dtFile.Rows.Count > 0 Then
Dim dr As DataRow = dtFile.Rows(0)
hlOrgChart.NavigateUrl = ruOrgChart.TargetFolder & "/" & dr.Item("FileName")
hlOrgChart.Text = dr.Item("FileName")
hlOrgChart.Visible = True
End If
EDIT: I believe, to remove the radio button section, remove:
<asp:RadioButtonList ID="rblOrgChart" runat="server" AutoPostBack="True">
<asp:ListItem ID="rblOrgChartY" runat="server" Value="1" Text="Yes (Please upload the organizational chart as a PDF file)"></asp:ListItem>
<asp:ListItem ID="rblOrgChartN" runat="server" Value="0" Text="No" ></asp:ListItem>
</asp:RadioButtonList>
and
<Triggers>
<asp:AsyncPostBackTrigger controlid="rblOrgChart" EventName="SelectedIndexChanged"/>
</Triggers>

listbox failed to pick up value when reloading the page

I'm trying to put a searchbox, a dropdownlist and lostbox control on my asp master page. Once a value is selected from the dropdownlist, the value passed to listbox;once some word is typed into the searchbox and enter is hit, the closest value is passed to the listbox.
My asp code for the control is below:
searchbox:
<asp:TextBox ID="TextBox1" runat="server" ToolTip="Enter Company" Width="120px">
dropdownlist:
<asp:DropDownList ID="DropDownListCI" runat="server" DataSourceID="SqlDataSource3" DataTextField="company" DataValueField="id" AppendDataBoundItems="true" AutoPostBack="True" width="160px">
<asp:ListItem Text="--Select One--" Value="" Selected="True" /> </asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="select company, id from table1 order by company">
</asp:SqlDataSource>
listbox:
<asp:ListBox ID="ListBox1" runat="server" DataTextField="company" DataValueField="id" Rows="1" Width="160px">
<asp:ListItem Text="--Null--" Value="" selected="true" />
</asp:ListBox>
data source from the searchbox is:
<asp:SqlDataSource ID="SqlDataSourceSE" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="select company, id from table1 where company like '%'+ #Company + '%'">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="Company" PropertyName="Text" />
</SelectParameters>
</asp:SqlDataSource>
datasource from dropdownlist is
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="select company, id from table1 where id=#id">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListCI" Name="ID" PropertyName="selectedvalue" />
</SelectParameters>
</asp:SqlDataSource>
and my vb code is below:
--Store session variable
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SelectionCI As String = Nothing
Dim SelectionSE As String = Nothing
If Not DropDownListCI.Text Is Nothing Then SelectionCI = DropDownListCI.Text
Session("SelectedCI") = SelectionCI
If Not TextBox1.Text Is Nothing Then SelectionSE = TextBox1.Text
Session("SelectedSE") = SelectionSE
End Sub
--page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Not Session("SelectedCI") Is Nothing Then DropDownListCI.Text = Session("SelectedCI").ToString
If Not Session("SelectedSE") Is Nothing Then TextBox1.Text = Session("SelectedSE").ToString
End If
If Not DropDownListCI.Text = "" Then ListBox1.DataSourceID = SqlDataSource1.ID
If Not TextBox1.Text = "" Then ListBox1.DataSourceID = SqlDataSourceSE.ID
End Sub
-----on change
Protected Sub DropDownListCI_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownListCI.SelectedIndexChanged
If Not DropDownListCI.SelectedIndex = 0 Then
TextBox1.Text = ""
ListBox1.DataSourceID = SqlDataSource1.ID
Else : ListBox1.SelectedIndex = 0
End If
End Sub
Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
If Not TextBox1.Text = "" Then
DropDownListCI.SelectedIndex = 0
ListBox1.DataSourceID = SqlDataSourceSE.ID
End If
End Sub
What I want to achieve is after I make a selection (say company A), when I refresh page, company A is still selected. Now it works well if company A is got through search box. But if I select company A from dropdownlist, then store the session variable, then refresh the page, it comes out company A is still selected in dropdownlist, but "--Null--" appears in listbox. I wonder what's the problem?
Thanks for any advice!
I finally realized that my page_load has a problem. The following is the correct page_load code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
If Not Session("SelectedCI") Is Nothing And Session("SelectedCI") <> "" Then
DropDownListCI.Text = Session("SelectedCI").ToString
ListBox1.DataSourceID = SqlDataSource1.ID
ElseIf Not Session("SelectedSE") Is Nothing And Session("SelectedSE") <> "" Then
TextBox1.Text = Session("SelectedSE").ToString
ListBox1.DataSourceID = SqlDataSourceSE.ID
End If
End Sub

How to assign value to the DropBox text propery?

I'm writing a program where user has 3 drop boxes to input date, month and a year. after user selects the values I concatenate them and check for valid By default when a page loads I need to assign a current day, month and year to each drop box accordingly. Then I check validity of the date and pass value to the database.
My problem is that when I assign the values to the text of DropBoxes upon the loading of the page they are becoming permanent. even if the index is changed the values which are passed to the database are the ones which assigned to them when the page is loaded.
I can't actually understand what am I doing wrong:
these are the code samples which I've used:
I populate them with a current date values using folowing code(on the page Load event):
Dim CurYear As Integer = DatePart("yyyy", Now)
Dim CurDate As Integer = DatePart("d", Now)
Dim CurMonth As String = Format(Today.Date, "MMMM")
Dim CurDate2 As Integer = DatePart("d", Now)
Dim CurMonth2 As String = Format(Now, "MM")
Dates.Text = CurDate
Monthe.Text = CurMonth
years.Text = CurYear
Month2.Text = CurMonth2
Dates2.Text = CurDate2
Than I had to synchronize the selected index of 2 the dropboxes which contain numerical value of the month and 2 digit format of the day, to to form the proper string for checking of the date
Protected Sub Months_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Months.SelectedIndexChanged
Month2.SelectedIndex = Months.SelectedIndex
TextBox3.Text = years.Text & "-" & Monthes.Text & "-" & Dates.Text
End Sub
Protected Sub Dates_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles Dates.SelectedIndexChanged
Dates2.SelectedIndex = Dates.SelectedIndex
TextBox3.Text = years.Text & "-" & Monthes.Text & "-" & Dates.Text
End Sub
And this is front end ASP code:
<asp:DropDownList ID="Dates" runat="server" autopostback="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem>1</asp:ListItem>
...
<asp:ListItem>26</asp:ListItem>
<asp:ListItem>27</asp:ListItem>
<asp:ListItem>28</asp:ListItem>
<asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>31</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Months" runat="server" autopostback="true" >
<asp:ListItem></asp:ListItem>
<asp:ListItem>January</asp:ListItem>
...
<asp:ListItem>November</asp:ListItem>
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="years" runat="server" autopostback="true" >
<asp:ListItem></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Dates2" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
<asp:ListItem>02</asp:ListItem>
....
<asp:ListItem>29</asp:ListItem>
<asp:ListItem>30</asp:ListItem>
<asp:ListItem>31</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Month2" runat="server" AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>01</asp:ListItem>
....
<asp:ListItem>11</asp:ListItem>
<asp:ListItem>12</asp:ListItem>
</asp:DropDownList>
Again, if I don't assign the default values to the boxes upon loading of the page it works perfectly. if i do, those values are fixed no mater what you choose
The comparevalidator:
<asp:UpdatePanel ID="UpdatePanel19" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox3" ValidationGroup="CompareValidatorDateTest" runat="server"></asp:TextBox>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Dates" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="Monthes" EventName="SelectedIndexChanged" />
<asp:AsyncPostBackTrigger ControlID="years" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
<asp:CompareValidator ID="CompareValidator3" Display="dynamic" ControlToValidate="TextBox3"
Type="Date" Operator="LessThanEqual" Text="Please enter a valid date" runat="server"
ValidationGroup="CompareValidatorDateTest"
I suppose you didnt use IsPostBack property while binding the dropdown with values on page load.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
// Bind your dropdown here here
End If

passing checkboxlist selected items as a concatenated string

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.

Get value of listitem on postback

I have two listitems and the postback and run a function.
<asp:RadioButtonList runat="server" CssClass="ccsw" ID="ccsw" AutoPostBack="true" RepeatDirection="Horizontal" OnSelectedIndexChanged="UpdateCharges">
<asp:ListItem Text="Credit Card"></asp:ListItem>
<asp:ListItem Text="Debit Card"></asp:ListItem>
</asp:RadioButtonList>
And it runs the function UpdateCharges
Sub UpdateCharges(ByVal sender As Object, ByVal e As System.EventArgs)
If ccsw_1.Checked Then
lblPayText.Text = "Payment Amount = £" & Session("strTotal_DebtCharge")
Else
lblPayText.Text = "Payment Amount = £" & Session("strTotal_Debt")
End If
End Sub
I need to find out which one is checked and then change the text of a label depending on that.
The code I have doesn't work i don't think .Checked works in this instance.
Any idea of how to get the value or text of the listitem?
Thanks
If Me.ccsw.SelectedIndex = 0 Then
lblPayText.Text = "Payment Amount = £" & Session("strTotal_DebtCharge")
Else
lblPayText.Text = "Payment Amount = £" & Session("strTotal_Debt")
End If

Resources