listbox selected items into textbox not working - asp.net

my vb.net will not use listbox1.selecteditems it always comes up with a blue line underneath even though when i search online everyone is using this.
my goal is to get the selected items and list them in a textbox
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim li As ListItem
For Each li In ListBox1.Items
If li.Selected Then
TextBox1.Text &= li.Text & vbCrLf
End If
UpdatePanel2.Update()
Next
End Sub
End Class

To determine the selection in a multi-selection list control
Loop through the control's Items collection and test the Selected property of every individual item.
For Each li In ListBox1.Items
If li.Selected Then
TextBox1.Text &= li.Text & vbCrLf
End If
Next
MSDN: To determine the selection in a multi-selection list control
SelectedItems is not available in ASP.Net, this property exists only for Winforms-Listbox Controls.

I think the problem here is that you're binding to the control immediately prior to trying to retrieve a selected value from it. When the control is initially bound to the datasource it won't have any selected items.
You need to split it out so that you bind the listbox when the page is loaded, then the user selects some things in that box, clicks your Button2, and the value of the textbox is updated on postback.
First, on page load:
Protected Sub Page_Load(object sender, EventArgs, e)
listcmd.Connection = conn1
conn1.Open()
listcmd.CommandText = "SELECT distinct B603SalesAsOFMASTER.SDESCR FROM B603SalesAsOFMASTER"
listda.Fill(saolist, "listboxtext")
Dim dt As DataTable = saolist.Tables("listboxtext")
ListBox1.DataSource = dt
ListBox1.DataValueField = "SDESCR"
ListBox1.DataMember = "SDESCR"
ListBox1.DataBind()
conn1.Close()
End Sub
Then, this code is run when the user clicks Button2
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
For i As Integer = 0 To ListBox1.SelectedItems.Count - 1
TextBox1.Text &= DirectCast(ListBox1.SelectedItems(i), DataRowView)(1).ToString & vbCrLf
Next
CheckBox1.Visible = True
TextBox1.Visible = True
End Sub

To view (Text Item in textbox)
textbox3.Text = listBox1.GetItemText(listBox1.SelectedItem);

Related

Maintain Tab index after post back with textchanged

I have 3 textboxes that have AutoPostBack = true. On postback it's losing it's focus. I've been searching and tried many things but nothing is working.
The code below is a snippet of what i'm trying to do.
basically this first snippet isn't grabbing anything. Does anyone know what i'm doing wrong here
**Side note I'm not using Update Panel i'm using LayoutItemNestedControlContainer
Dim ctrl = From control In wcICausedPostBack.Parent.Controls.OfType(Of WebControl)()
Where control.TabIndex > indx
Select control
Protected Sub txtDEPTH_TextChanged(sender As Object, e As EventArgs) Handles txtDEPTH.TextChanged
UpdateProductTemp()
txtDEPTH.Focus()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
Dim wcICausedPostBack As WebControl = CType(GetControlThatCausedPostBack(TryCast(sender, Page)), WebControl)
Dim indx As Integer = wcICausedPostBack.TabIndex
Dim ctrl = From control In wcICausedPostBack.Parent.Controls.OfType(Of WebControl)()
Where control.TabIndex > indx
Select control
ctrl.DefaultIfEmpty(wcICausedPostBack).First().Focus()
End If
End Sub
Protected Function GetControlThatCausedPostBack(ByVal page As Page) As Control
Dim control As WebControl = Nothing
Dim ctrlname As String = page.Request.Params.[Get]("__EVENTTARGET")
If ctrlname IsNot Nothing AndAlso ctrlname <> String.Empty Then
control = page.FindControl(ctrlname)
Else
For Each ctl As String In page.Request.Form
Dim c As Control = page.FindControl(ctl)
If TypeOf c Is TextBox OrElse TypeOf c Is DropDownList Then
control = c
Exit For
End If
Next
End If
Return control
End Function
Which version are you using? Because, when I try to set focus() of a Textbox, the compiler gives me an error, because there is no such method. However, HTML provides an attribute, which auto focuses an focusable element.
Solution:
TextBoxToSetFocus.Attributes.Add("autofocus", "")
Regards,
Maheshvara

items of listbox losing styles after postback

I have a ListBox. When I bind data I need to distinguish some items by color. There is how I do it
Protected Sub ListBox_DataBound(ByVal sender As Object, ByVal e As EventArgs)
Dim lb As ListBox = CType(sender, ListBox)
For Each li As ListItem In lb.Items
If someFlag = True Then
li.Attributes("style") += "color: red;"
End If
Next
End Sub
But when I do postback these styles is lost. How I can save style between postback?
EDIT: Inside Page_Load I don't do anything with this listbox. I fill listbox when occur event selectIndexChange for ddl. but when I click on linkbutton
Private Sub lnkbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkBtn.Click
Dim selectedItems As ArrayList = New ArrayList
For Each itm As ListItem In listbox1.Items
If itm.Selected = True Then
selectedItems.Add(itm)
End If
Next
For i As Int32 = 0 To selectedItems.Count - 1
listbox1.Items.Remove(selectedItems(i))
listbox2.Items.Add(selectedItems(i))
Next
End Sub
after this event items of listbox1 lost styles

how to get the text value of dynamically created textbox

I want to get the value of my textbox that I created dynamically when I click a button
I need to do this cause the value of my textbox is used for retrieve data from database
how could I achieved this thing??
the flow is Button click - creating textbox - filling textbox with value - Button Click - Get Text of textbox
here is my code to make the textbox
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For i As Integer = 0 To 4
textbox = New TextBox With {.ID = "TextBox" & i}
plchld.Controls.Add(textbox)
Next
End Sub
I have tried something like this but the code didn't work
Protected Sub OkButton_Click(sender As Object, e As EventArgs) Handles OkButton.Click
Dim a(5) As String
For i As Integer = 0 To 4
a(i) = CType(plchld.FindControl("Textbox" & i), TextBox).Text
Next
End Sub
thanks in advance for any help
edit for the answer
I've found the way to solve this. I use request.form to get the value of my textbox.
Thanks for anyone that participating
Regards,
Julian
This is how I have done in my asp.net application.
Creating dynamic control
TextBox txtDate = new TextBox();
txtDate.EnableViewState = true;
txtDate.ID = "PreixValue" + 1;
txtDate.Text = "07 Feb 2014"
pnl.controls.add(txtdate);
To retrieve the value from that textbox
DateTime datefrom = DateTime.Now ;
for (int cnt = 0; cnt < Request.Form.Count; cnt++)
{
if (Request.Form.AllKeys[cnt].Contains("Prefixvalue"))
{
int ParamStartPoint = Request.Form.AllKeys[cnt].IndexOf("Prefix") + 4;
int ParamNameLength = Request.Form.AllKeys[cnt].Length - ParamStartPoint;
string[] ControlName = Request.Form.AllKeys[cnt].Substring(ParamStartPoint, ParamNameLength).Split('$');
if (ControlName[0] == "Date From")
{
datefrom = DateTime.Parse(Request.Form[cnt]);
//datefrom has value now
}
}
}
This is how I have done in my web application, but there may be other ways achieve this.
basically when you create Dynamic control in webform this will be available through Request.Form.
hope this helps you.
Protected Sub OkButton_Click(sender As Object, e As EventArgs) Handles OkButton.Click
Dim a(5) As String
For i As Integer = 0 To 4
Dim anotherObj As TextBox = Me.Controls.Item("Textbox" & i)
a(i) =anotherObj.Text
Next
The issue is that dynamic controls are lost on a postback so when the OkButton click event is handled, there is nothing inside your plchld control. You must recreate your controls with the same ID on postback if you want to retrieve the text in the textboxes.
Using your code, all you need to do is on postback determine if the textboxes were created and if so, recreate them.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Determine if the text boxes were created and if so, recreate them.
If CBool(ViewState("TextBoxesCreated")) Then
CreateTextBoxes()
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
CreateTextBoxes()
ViewState("TextBoxesCreated") = True
End Sub
Private Sub CreateTextBoxes()
For i As Integer = 0 To 4
plchld.Controls.Add(New TextBox With {.ID = "TextBox" & i})
Next
End Sub
Protected Sub OkButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OkButton.Click
Dim a(4) As String
For i As Integer = 0 To 4
a(i) = CType(plchld.FindControl("Textbox" & i), TextBox).Text
Next
End Sub
I don't know the full extent of what you are doing but I would suggest not creating them dynamically if you don't need to. Just show or hide the textboxes instead.
Reference: http://www.codeproject.com/Articles/3684/Retaining-State-for-Dynamically-Created-Controls-i

Maintaining Checkbox State in a Listview Control Pagination ASP.NET

I Have a web form in a asp.net web form 3.5. The listview has a checkbox on the item template, I am trying to retain the state of the checkboxes through pagination . Once I can page through records and preserver this state I need to send this to a print page which takes those ids...I have this working, but it will print only the records on each pagination. Please see live website:
http://rgvpreferred.com/ProviderSearch.aspx
Can you please check my code and suggest how can this be done, the code below is not working.
Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListView1.ItemCommand
Dim myButtonPrint1 As Button = CType(ListView1.FindControl("printButton1"), Button)
If e.CommandSource Is myButtonPrint1 Then
Dim recordsId As New List(Of String)
For Each lvi1 As ListViewItem In ListView1.Items
Dim chb1 As CheckBox = IIf(lvi1.FindControl("CheckBoxPrintProvider1") Is Nothing, IIf(lvi1.FindControl("CheckBoxPrintProvider3") Is Nothing, lvi1.FindControl("CheckBoxPrintProvider4"), lvi1.FindControl("CheckBoxPrintProvider3")), lvi1.FindControl("CheckBoxPrintProvider1"))
If chb1.Checked = True Then
Dim param1 As String
param1 = DirectCast(lvi1.FindControl("lblId1"), Label).Text
recordsId.Add(param1)
End If
Next
' Store in session to be pulled out in the Printable Page
Session("Records") = recordsId
Response.Redirect("PrintableProviderList.aspx")
End If
End Sub
'Trying to Preserve states
Private ReadOnly Property IDs() As List(Of Integer)
' Create a list of ID's that are selected. ID's is the primary
' Key for this table
Get
If Me.ViewState("IDs") Is Nothing Then
Me.ViewState("IDs") = New List(Of Integer)()
End If
Return CType(Me.ViewState("IDs"), List(Of Integer))
End Get
End Property
Protected Sub AddRowstoIDList()
' Loop through all the current items in the Listview
For Each lvi As ListViewDataItem In ListView1.Items
' Find the checkbox in each row
Dim chkSelect As CheckBox = CType(lvi.FindControl("CheckBoxPrintProvider1"), CheckBox)
' If the checkbox is ticked then add the corresponding ID to our private
' list
If (Not (chkSelect) Is Nothing) Then
' Get the ID from the datakeynames property
Dim ID As Integer = Convert.ToInt32(ListView1.DataKeys(lvi.DisplayIndex).Value)
If (chkSelect.Checked AndAlso Not Me.IDs.Contains(ID)) Then
' Add the ID to our list
Me.IDs.Add(ID)
ElseIf (Not chkSelect.Checked AndAlso Me.IDs.Contains(ID)) Then
' Not checked - remove the ID from our list
Me.IDs.Remove(ID)
End If
End If
Next
End Sub
Protected Sub ListView1_PagePropertiesChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.PagePropertiesChangingEventArgs) Handles ListView1.PagePropertiesChanging
AddRowstoIDList()
End Sub
Protected Sub ListView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewSortEventArgs) Handles ListView1.Sorting
AddRowstoIDList()
End Sub
Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
' Get each Listview Item on DataBound
Dim lvi As ListViewDataItem = e.Item
If (lvi.ItemType = ListViewItemType.DataItem) Then
' Find the checkbox in the current row
Dim chkSelect As CheckBox = CType(lvi.FindControl("CheckBoxPrintProvider1"), CheckBox)
' Make sure we're referencing the correct control
If (Not (chkSelect) Is Nothing) Then
' If the ID exists in our list then check the checkbox
Dim ID As Integer = Convert.ToInt32(ListView1.DataKeys(lvi.DisplayIndex).Value)
chkSelect.Checked = Me.IDs.Contains(ID)
End If
End If
End Sub
you have to save the selected checkboxes before pagination .
see this link. it should help you:
http://evonet.com.au/maintaining-checkbox-state-in-a-listview/

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

Resources