Writing a passed Array via session into Label isn't working - asp.net

I am trying to take an array of string (Filled from a listbox on a previous page and passed via Session) and display it in a label,this is how i got the array:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim x = ListBox1.GetSelectedIndices.Count
Dim ListPNames(x) As String
Dim i As Integer
i = 0
For Each item As String In ListBox1.GetSelectedIndices
ListPNames(i) = (ListBox1.SelectedItem).ToString
i = i + 1
Next
Session("SlctdPhones") = ListPNames(x)
Response.Redirect("CheckOut.aspx")
End Sub
And this is how i am trying to display it :
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim i As Integer
Label3.Text = ""
For i = 0 To SlctdPhones.Length - 1
Label3.Text += SlctdPhones(i).ToString() + Environment.NewLine
Next
End Sub
It is giving me an error :Object reference not set to an instance of an object. when it reaches the SlctdPhones.Length - 1 Line!!
i don't know how i can fix it ,also is my array code correct(Is everything being stored correctly in it?)

You declare the For loop like this:
For Each item In ...
But then never use the item variable in the body of the loop. Instead, you keep using the same SelectedItem property. You want to change that whole method to look like this:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles CheckOut.Click
Dim PNames As New List(Of String)()
For Each index As Integer In ListBox1.GetSelectedIndices
PNames.Add(ListBox1.Items(index).Value)
Next
Session("SlctdPhones") = PNames
Response.Redirect("CheckOut.aspx")
End Sub
With that fixed, the Page_Load can do this:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim SlctdPhones As List(Of String) = TryCast(Session.Item("SlctdPhones"), List(Of String))
If SlctdPhones Is Nothing OrElse SlctdPhones.Length = 0 Then
'Something went wrong here!
Return
End If
Label3.Text = String.Join("<br/>", SlctdPhones.ToArray())
End Sub
But I'd really love to see you use a data control rather than stuffing <br/>s into a label. Here's markup for a ListView:
<asp:ListView ID="ListView1" runat="server">
<LayoutTemplate>
<ul>
<asp:PlaceHolder ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li><%# Container.DataItem.ToString() %></li>
</ItemTemplate>
<EmptyDataTemplate>
<p>Nothing here.</p>
</EmptyDataTemplate>
</asp:ListView>
And then Page_Load is even simpler:
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ListView1.DataSource = Session.Item("SlctdPhones")
ListView1.DataBind()
End Sub

On display page, use Literal instead of Label
Dim SlctdPhones() As String = CType(Session.Item("SlctdPhones"), Array)
Dim result as String = string.Join("<br>", SlctdPhones) 'Instead of <br> try Environment.NewLine as well
YourLitetal = result
Hope this helps!

Related

ChekBoxList Not Noticing Selected, and not displaying value

Not picking up that something is selected, and not displaying the value.
When I debug the code and step-in:
VBCODE:
When Debugging the "li" after Each holds a value(ex286)
when I go to Item and open the box I get this:
Item = Argument not specified for parameter 'index' of 'Public ReadOnly Default Property Item(index As Integer) As System.Web.UI.WebControls.ListItem'.
Item = In order to evaluate an indexed property, the property must be qualified and the arguments must be explicitly supplied by the user.
the "li" after If holds a value(ex286), but the Selected is "FALSE" Do not know why.
After the = li is the text and the Value(286)
Another thing it only gives me the value for the first box value not the rest if I click them.
Protected Sub LinkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton.Click
For Each li As ListItem In CheckBoxList.Items
If li.Selected Then
Texttext.Text = li.Value
Else
Texttext.Text = "Give Up Loser!"
End If
NextEnd Sub
ASCX FILE
<asp:CheckBox ID="CheckBoxSelectAll" runat="server" Text="Select All" AutoPostBack="True" />
<asp:CheckBoxList ID="CheckBoxList" runat="server"
DataSourceID="ObjectDataSource1" DataTextField="Name" DataValueField="Id"
RepeatColumns="3" ></asp:CheckBoxList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetStuff"
DataObjectTypeName ="DataTransfer.TheData"
TypeName="BusinessDelegate.DataBusinessDelegate">
</asp:ObjectDataSource>
<asp:LinkButton ID="LinkButton" runat="server" Text="Here"></asp:LinkButton>
<asp:Label ID ="Texttext" runat="server" Text=""></asp:Label>
I have tried a few items from online but nothing worked correctly.
Get all selected values of CheckBoxList in VB.NET
ASP.NET, VB: checking which items of a CheckBoxList are selected
I am not sure what you are trying to achieve with this.
The below code might work for you.
Protected Sub LinkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton.Click
Dim cbChecked As Boolean
For lItem = 0 To CheckBoxList.Items.Count - 1
cbChecked = CheckBoxList.GetItemChecked(lItem)
If cbChecked Then
Texttext.Text = CheckBoxList.GetItemText(lItem)
Else
Texttext.Text = "Give Up Loser!"
End If
Next
End Sub
When you run this above code, if the last check box is not checked then you will end up with
'Give Up Loser!' in the 'Texttext' text box.
You can get the number of checked boxes in the list by using the below code
Protected Sub LinkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton.Click
Dim checkedBoxes = CheckBoxList.CheckedItems
Dim checkedBoxesCount = checkedBoxes.Count
For Each lItems In checkedBoxes
Dim chkdCheckBoxName = lItems.ToString
Next
End Sub
Try this below code to write the values of checked boxes in the text box.
Protected Sub LinkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton.Click
Texttext.Text = "" 'clearing the text box
Dim checkedBoxes = CheckBoxList.CheckedItems
Dim checkedBoxesCount = checkedBoxes.Count
For Each lItems In checkedBoxes
Dim chkdCheckBoxName = lItems.ToString
Texttext.Text = Texttext.Text & " | " & chkdCheckBoxName
Next
If checkedBoxesCount = 0 Then
Texttext.Text = "Give Up Loser!"
End If
End Sub
Above code is based on System.Windows.Forms.CheckedListBox

Page lifecycle is causing an error with user controls within sub

Thanks to #Angkor Wat I achived a major step towards my goal: dynamic adding of pieces of strings to a string. But I came across another thing I cannot solve.
Here is the script:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="addtostring.aspx.vb" Inherits="demo_addtostring" %>
<!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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p><asp:textbox id="tb" runat="server"></asp:textbox></p>
<asp:Panel ID="tbPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
</html>
This is the code behind:
Partial Class demo_addtostring
Inherits System.Web.UI.Page
Public Property gesStr As String
Set(value As String)
ViewState("gesStr") = value
End Set
Get
Dim o As Object = ViewState("gesStr")
If o Is Nothing Then
Return ""
Else
Return o
End If
End Get
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
Else
gesStr = "1;"
End If
tb.Text = gesStr
Dim iButton As New Button
iButton.Text = "add"
iButton.CommandArgument = "1;"
iButton.CommandName = "1;"
AddHandler iButton.Click, AddressOf add
tbPanel.Controls.Add(iButton)
If Page.IsPostBack Then
Else
anzeige()
End If
End Sub
Private Sub add(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As Button = DirectCast(sender, Button)
Dim addString As String = myButton.CommandArgument
gesStr += addString
tb.Text = gesStr
anzeige()
End Sub
Private Sub anzeige()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
Dim anzeigeDiv As New System.Web.UI.HtmlControls.HtmlGenericControl("div")
Dim anzLabel As New Label
anzLabel.Text = gesArray(xLauf)
anzeigeDiv.Controls.Add(anzLabel)
Dim iButton2 As New Button
iButton2.Text = xLauf.ToString
iButton2.ID = "test" & xLauf.ToString
iButton2.CommandArgument = "1;"
iButton2.CommandName = "1;"
AddHandler iButton2.Click, AddressOf add
anzeigeDiv.Controls.Add(iButton2)
tbPanel.Controls.Add(anzeigeDiv)
Next
End Sub
End Class
Clicking on the add-button should add "1;" to gesStr - the dynamic loop-generated buttons should do the same -.- Does anyone have an idea? I would be very thankful for help...
In order for the postback to know about the event handler from the button, the button needs to be recreated prior to the point in the lifecycle where the handler is invoked. In other words, you will always need to recreate the buttons within your Page_Load.
Here is a modification to your code which works:
<form id="form1" runat="server">
<div>
<p><asp:textbox id="tb" runat="server"></asp:textbox></p>
<br />
<asp:Button runat="server" ID="btnAdd" Text="add" CommandArgument="1;" />
<asp:Panel ID="tbPanel" runat="server"></asp:Panel>
</div>
</form>
And code-behind:
Public Property gesStr As String
Get
Dim o As Object = ViewState("gesStr")
If o Is Nothing Then
Return ""
Else
Return DirectCast(o, String)
End If
End Get
Set(value As String)
ViewState("gesStr") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
gesStr = "1;"
End If
tb.Text = gesStr
End Sub
Private Sub add(ByVal sender As Object, ByVal e As CommandEventArgs) Handles btnAdd.Command
Dim addString As String = e.CommandArgument
gesStr += addString
tb.Text = gesStr
CreateNewButton(tbPanel.Controls.Count, addString.Substring(0, addString.Length - 1))
End Sub
Protected Overrides Sub CreateChildControls()
MyBase.CreateChildControls()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
CreateNewButton(xLauf, gesArray(xLauf))
Next
End Sub
Private Sub CreateNewButton(ByVal xLauf As Integer, ByVal labelText As String)
Dim anzeigeDiv As New Panel
anzeigeDiv.ID = "div" & xLauf.ToString()
Dim anzLabel As New Label
anzLabel.Text = labelText
anzeigeDiv.Controls.Add(anzLabel)
Dim iButton2 As New Button
iButton2.Text = xLauf.ToString
iButton2.ID = "test" & xLauf.ToString()
iButton2.CommandArgument = "1;"
iButton2.CommandName = "1;"
AddHandler iButton2.Command, AddressOf add
anzeigeDiv.Controls.Add(iButton2)
tbPanel.Controls.Add(anzeigeDiv)
End Sub
I've moved the add button, which will always exist, into the aspx page, so that the dynamic panel will only contain the buttons which have been added based on gesStr value.
Dynamic controls must be re-created in every postback see this article for more information.

Using DropDownList in FromView control

I'm trying to get a drop down list control to work in FormView. I need to have the list be a filtered view of a certain table and still be bound to a field in the data I'm editing. I've tried setting the item data programatically, ant that works but then the data binding
doesn't work, It tries to insert null into the database.
This is the code I've tried. I've also tried doing the same thing in several other events, it still tries to insert null into the database.
<asp:DropDownList ID="lstManagers" runat="server"
OnDataBound ="ManagersLoad"
SelectedValue='<%# Bind("UserName") %>' Width="100%"
DataSourceID="TimeOff" DataTextField="UserName" DataValueField="UserName">
</asp:DropDownList>
Protected Sub ManagersLoad(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
'get list of managers
Using ef As New TimeOffData.TimeOffEntities
For Each item As ListItem In lst.Items
Dim li As ListItem = item
item.Text = (From x In ef.TimeOffUsers Where x.UserName = li.Value Select x.FirstName & " " & x.LastName).FirstOrDefault
Next
End Using
End Sub
I took all the data binding stuff of the control and just decide it would be easier to do it manually. I've changed the code to this,
Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
e.Values.Item("ManagerName") = lst.SelectedValue
End Sub
Protected Sub ManagersLoad(ByVal sender As Object, ByVal e As System.EventArgs)
Dim lst As DropDownList = FormView1.FindControl("lstManagers")
'get list of managers
Using ef As New TimeOffData.TimeOffEntities
Dim mng = From x In ef.TimeOffUsers Where x.IsManager = True
For Each item In mng
lst.Items.Add(New ListItem(item.FirstName & " " & item.LastName, item.UserName))
Next
End Using
End Sub

Pass GridView Cell Value to Sub Routine in ASP.NET / VB.NET

I have a GridView with Cell 0 containing the ID that I need to pass to a Public Sub.
I cannot figure out how to pick the value from Cell 0 in order to pass it to the Sub. I have tried experimenting (see the Dimmed EventID below) but have failed. Here is my code:
Protected Sub gvAppointmentsCalls_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvAppointmentsCalls.RowCommand
Dim EventID As String = gvAppointmentsCalls.Rows(e.RowIndex).Cells(0).Text
If e.CommandName = "gvAdd2Outlook" Then
Send_iCal_Call(EventID)
End If
End Sub
If I type the value directly e.g. Send_iCal_Call(123) then it works perfectly.
Public Sub Send_iCal_Call(ByRef Event_ID As Integer)
' My code in here
End Sub
Use the CommandArgument to pass the ID to the RowCommand-Handler.
For example:
CommandName="gvAdd2Outlook" CommandArgument='<%# Bind("EventID")%>'
In my opinion you should obtain your ID value within GridView's DataKeyNames property. You should define it in your grid markup this property like here
<asp:GridView DataKeyNames="EvenID">
and then will access it in code behind:
Protected Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName = "gvAdd2Outlook" Then
Dim EventIDString As String = GridView1.DataKeys.Item(e.RowIndex).Value.ToString()
Dim EventID As Integer
If Integer.TryParse(EventIDString, EventID) = False Then Throw New ArgumentException("Wrong EventID=" & EventID)
Send_iCal_Call(EventID)
End If
End Sub

pass the id on a link click

i have a web application for video uploading,In that i want to show the video in the link click.i wrote a function for to show the video.i want to pass the id of video into the function .How can i Do that?
Can any one help Me?
This is my code
Private Function
GetSpecificVideo(ByVal i As Object) As
DataTable
'pass the id of the video
Dim connectionString As String =
ConfigurationManager.ConnectionStrings("UploadConnectionString")
.ConnectionString
Dim adapter As New SqlDataAdapter("SELECT FileName,
FileID,FilePath " + "FROM FileM WHERE
FileID = #FileID", connectionString)
adapter.SelectCommand.Parameters.Add("#FileID",
SqlDbType.Int).Value = DirectCast(i, Integer)
Dim table As New DataTable()
adapter.Fill(table)
Return table
End Function
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
Repeater1.DataSource = GetSpecificVideo(****here i want to get the ID****)
'the video id (2 is example)
Repeater1.DataBind()
End Sub
of the many ways one is to set CommandArgument for the link (or rather button as your code seems).
ASPX:
<ItemTemplate>
<asp:LinkButton ID="lnkVideo" runat="server"
CommandArgument='<%# Eval("VideoID")%>'
OnClick="ButtonShowVideo_Click">Watch Video</asp:LinkButton>
</ItemTemplate>
Code:
private sub void GetVideos()
'GET VIDEO(S)
'CREATE LINKS OR IF IN GRID GET LINKS AND SET COMMAND ARGUMENT FOR IT
lnk1.CommandArgument = ID_OF_VIDEO
end sub
now handle click:
Protected Sub ButtonShowVideo_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles ButtonShowVideo.Click
var btn = sender as Button 'or Link or LinkButton
if(btn is not null) then
if(NOT string.IsNullOrEmpty(btn.CommandArgument)) then
var vid = Convert.ToInt32(btn.CommandArgument)
Repeater1.DataSource = GetSpecificVideo(vid)
Repeater1.DataBind()
end if
end if
End Sub

Resources