listbox failed to pick up value when reloading the page - asp.net

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

Related

Persisting Checkbox State when Paging Gridview

In a nutshell, I am trying to maintain the CheckBox state on a GridView while paging. I am successfully tracking the CheckBox states in the ViewState (using an ArrayList on the row IDs) and I can successfully perform an action on all the checked rows on multiple pages.
However, once I go to a new page and then page back, the checked CheckBoxes are no longer checked (though the row ID still exists in the ArrayList in the ViewState). I have to assume this has something to do with the page life cycle.
I have read the entire ASP.NET Page Life Cycle Overview and tried binding the GridView in the PreRender event (and not binding the GridView at all) which didn't work either. All the examples I found online were loading the GridView DataSource from code behind using a DataTable filled from a SQLDataAdapter. I am using a DataSourceID (from a SQLDataSource) assigned directly to the GridView.
I still can't seem to determine why this is failing. Thanks in advance for your time.
ASPX Page
<asp:SqlDataSource ID="sdsAdminIntakes" runat="server" CancelSelectOnNullParameter="false"
Connectionstring="<%$ ConnectionStrings:MyAppSiteDB %>"
ProviderName="<%$ ConnectionStrings:MyAppSiteDB.ProviderName %>"
SelectCommand="admin_intakes_search"
SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="specialist_id" />
<asp:Parameter Name="caller_name" />
<asp:Parameter Name="case_number" />
<asp:Parameter Name="case_status" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="grdAdminIntakes" runat="server"
DataKeyNames="intake_id" DataSourceID="sdsAdminIntakes"
AutoGenerateColumns="False" AllowSorting="True"
AllowPaging="True" PageSize="20">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkAll" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkIntake" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="specialist_full_name" HeaderText="Current Specialist"
SortExpression="specialist_full_name" >
</asp:BoundField>
<asp:BoundField DataField="caller_name" HeaderText="Caller"
SortExpression="caller_name" >
</asp:BoundField>
<asp:BoundField DataField="case_number" HeaderText="Case #"
SortExpression="case_number" >
</asp:BoundField>
<asp:BoundField DataField="cmp_status" HeaderText="Case Status"
SortExpression="case_status" ItemStyle-CssClass="case_status" >
</asp:BoundField>
</Columns>
</asp:GridView>
ASPX.VB Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
grdAdminIntakes.DataBind()
End If
End Sub
Private Sub grdAdminIntakes_PageIndexChanging(sender As Object, e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdAdminIntakes.PageIndexChanging
GetCheckboxState()
grdAdminIntakes.PageIndex = e.NewPageIndex
grdAdminIntakes.DataBind()
SetCheckboxState()
End Sub
Private Sub GetCheckboxState()
Dim lstArray As ArrayList
If ViewState("SelectedRecords") IsNot Nothing Then
lstArray = DirectCast(ViewState("SelectedRecords"), ArrayList)
Else
lstArray = New ArrayList()
End If
Dim chkAll As CheckBox = DirectCast(grdAdminIntakes.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)
For i As Integer = 0 To grdAdminIntakes.Rows.Count - 1
If chkAll.Checked Then
If Not lstArray.Contains(grdAdminIntakes.DataKeys(i).Value) Then
lstArray.Add(grdAdminIntakes.DataKeys(i).Value)
End If
Else
Dim chk As CheckBox = DirectCast(grdAdminIntakes.Rows(i).Cells(0).FindControl("chkIntake"), CheckBox)
If chk.Checked Then
If Not lstArray.Contains(grdAdminIntakes.DataKeys(i).Value) Then
lstArray.Add(grdAdminIntakes.DataKeys(i).Value)
End If
Else
If lstArray.Contains(grdAdminIntakes.DataKeys(i).Value) Then
lstArray.Remove(grdAdminIntakes.DataKeys(i).Value)
End If
End If
End If
Next
ViewState("SelectedRecords") = lstArray
End Sub
Private Sub SetCheckboxState()
Dim currentCount As Integer = 0
Dim chkAll As CheckBox = DirectCast(grdAdminIntakes.HeaderRow.Cells(0).FindControl("chkAll"), CheckBox)
chkAll.Checked = True
Dim lstArray As ArrayList = DirectCast(ViewState("SelectedRecords"), ArrayList)
For i As Integer = 0 To grdAdminIntakes.Rows.Count - 1
Dim chk As CheckBox = DirectCast(grdAdminIntakes.Rows(i).Cells(0).FindControl("chkIntake"), CheckBox)
If chk IsNot Nothing Then
chk.Checked = lstArray.Contains(grdAdminIntakes.DataKeys(i).Value)
If Not chk.Checked Then
chkAll.Checked = False
Else
currentCount += 1
End If
End If
Next
End Sub
After several more hours of research, I was finally able to get this working by moving the SetCheckboxState() out of the grdAdminIntakes_PageIndexChanging event and into the grdAdminIntakes_DataBound event.

Formview cascading dropdown issue

I'm working on a Formview where in the EditTemplate, I have 1 dropdownlist dependent on another dropdownlist value.
I've looked at some examples and have found this one to be the most concise and I am working off of it:
http://mikepope.com/blog/AddComment.aspx?blogid=1629
It's pretty straight-forward but it's not working for my ddl. Can you tell me what I am missing or not implementing properly? I have removed some of the code in order to troubleshoot but still, nothing. For example, I am not setting the selectedValue as nothing is being returned...
Any advice would be appreciated.
Thanks
HTML:
<EditItemTemplate>
...
...
...
<tr>
<td colspan="6" align="left">
<asp:DropDownList ID="ddTeams" runat="server" CssClass="myDropDownIndent" DataSourceID="sqlGetTeams" DataTextField="Team" DataValueField="Team" SelectedValue='<%# DetermineTeamValue(Eval("Team")) %>' AutoPostBack="true" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
</td>
<td colspan="4" align="left">
<asp:DropDownList ID="DropDownOwner" runat="server" CssClass="myDropDown" DataSourceID="sqlGetMembers2" DataTextField="EmployeeName" DataValueField="EmployeeName" OnSelectedIndexChanged="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="sqlGetMembers2" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectDashboardConnectionString %>"
SelectCommand="usp_GetMembers" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:Parameter Name="Type" />
<asp:Parameter Name="TeamID" />
</SelectParameters>
</asp:SqlDataSource>
</td>
</tr>
Code Behind:
Protected Sub fvTask_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles fvTask.DataBound
If fvTask.CurrentMode = FormViewMode.Edit Then
Dim dv As System.Data.DataRowView = fvTask.DataItem
Dim ddTeams2 As DropDownList = fvTask.FindControl("ddTeams")
Dim DropDownOwner As DropDownList = fvTask.FindControl("DropDownOwner")
Dim a As String = "A"
Dim dsc As SqlDataSource = fvTask.FindControl("sqlGetMembers2")
dsc.SelectParameters("TeamID").DefaultValue = String.Empty
dsc.SelectParameters("Type").DefaultValue = String.Empty
DropDownOwner.DataBind()
'If Not IsDBNull(dv("EmployeeName")) Then
' DropDownOwner.SelectedValue = dv("EmployeeName")
'End If
End If
Catch ex As Exception
ErrMessage = ex.ToString
End Try
End Sub
So, my 2nd dropdownlist is null.

Index was out of range. Must be non-negative and less than the size of the collection parameter

I am getting this error while trying to disable the first radio button on the radiobutton list using the vb code:
RadioButtonList1.Items(0).Enabled = False
Here is the aspx code
<td class="TDLR">
<asp:RadioButtonList ID="RadioButtonList1" runat="server" DataSourceID="SqlFollow" DataTextField="FollowDesc" DataValueField="FollowID">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SqlFollow" runat="server"
ConnectionString="<%$ ConnectionStrings:SampleConnectionString %>"
SelectCommand="Select FollowID, FollowDesc FROM FollowUp WHERE FollowID > 30">
</asp:SqlDataSource>
</td>
Check the Items.Count first:
EDIT : Try the code in Page_PreRender like below:
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If RadioButtonList1.Items.Count > 0 Then
RadioButtonList1.Items(0).Enabled = False
End If
End Sub

I am having trouble getting my listbox to populate with the output from a sql query

I can’t seem to figure out where I went wrong here. I have two list boxes the first pulls its data from a stored procedure on a sql server. the second list box is supposed to populate when the an item in the first list box is selected. the second list box’s stored procedure should be passed the text of the selected item when that item in the first list box has been clicked. the problem is that that second list box is not populating. I would appreciate any helpful feedback or possibly an easier way of getting done what I am trying to do.
ASP.NET:
<asp:ListBox ID="ListBox1" runat="server" DataSourceID="LOCATION" DataTextField="L_Name" DataValueField="L_Name" AutoPostBack="True"></asp:ListBox>
<asp:SqlDataSource ID="LOCATION" runat="server" ConnectionString="<%$ ConnectionStrings:SAMC_2ConnectionString %>" SelectCommand="L_Get" SelectCommandType="StoredProcedure"></asp:SqlDataSource>
<asp:ListBox ID="ListBox2" runat="server" Height="150px" Width="200px" AutoPostBack="True" DataTextField="C_Name" DataValueField="C_Name" />
<asp:SqlDataSource ID="CompByLocal" runat="server" ConnectionString="<%$ ConnectionStrings:SAMC_2ConnectionString %>" SelectCommand="L_Get_C" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="ListBox1" DefaultValue="" Name="L_Name" PropertyName="SelectedValue" Type="String" />
<asp:Parameter Name="L_ID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
VB.NET:
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
Dim val As String = ListBox1.Items(ListBox1.SelectedIndex).ToString
TextBox1.Text = val
ListBox2.Items.Clear()
ListBox2.DataSource = CompByLocal
ListBox2.DataBind()
End Sub
My advice would be ditch the SqlDataSources and do it all in the back end - you can then be a lot more precise about when things occur in my experience. Ive done my best to write the necessary code below however my native tongue is C# - Ive used an online converter so please forgive any minor syntax errors.
ASPX:
<asp:ListBox ID="ListBox1" runat="server" DataTextField="L_Name" DataValueField="L_Name" AutoPostBack="True"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server" Height="150px" Width="200px" AutoPostBack="True" DataTextField="C_Name" DataValueField="C_Name" />
.VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
if (IsPostback) return
Dim results As New DataTable()
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SAMC_2ConnectionString "))
connection.Open()
Using command As New SqlCommand("L_Get", connection)
command.CommandType = CommandType.StoredProcedure
results.Load(command.ExecuteReader())
End Using
End Using
ListBox1.DataSource = results;
ListBox1.DataBind();
End Sub
Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim results As New DataTable()
Using connection As New SqlConnection(ConfigurationManager.ConnectionStrings("SAMC_2ConnectionString "))
connection.Open()
Using command As New SqlCommand("L_Get_C", connection)
command.CommandType = CommandType.StoredProcedure
command.Parameters.AddWithValue("L_ID",ListBox1.SelectedValue)
results.Load(command.ExecuteReader())
End Using
End Using
ListBox2.DataSource = results
ListBox2.DataBind()
End Sub

VB.net. how to do databind for the all dropdownlist in repeater

I have a dropdownlist in my repeater, the dropdownlist is databound by a datasource. Originally all the dropdownlist will have all the same item option. I try to do if one of the showing dropdownlist is selected one option, then in other dropdownlist this option will disapper.
here is the asp:
<asp:Repeater ID="UnitMatchRepeater" runat="server" DataSourceID="OldUnitsDataSource" >
<ItemTemplate>
<tr>
<td>
<asp:Label ID="OldUnitNumber" runat="server" Text='<%# Eval("Vehicle")%>' value='<%#Container.DataItem("LinkNumber") %>'></asp:Label>
</td>
<td> </td>
<td>
<asp:DropDownList ID="NewUnitsDropDownBox" runat="server" DataSourceID="NewUnitsDataSource" DataTextField="UnitNumber"
DataValueField="LinkNumber" OnDataBound="call_it" AutoPostBack="true" value='<%# Container.DataItem("LinkNumber")%>'></asp:DropDownList>
</td>
<br/>
</tr>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="OldUnitsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:minotaurSQLConnectionString %>">
</asp:SqlDataSource>
<br />
<asp:SqlDataSource ID="NewUnitsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:minotaurSQLConnectionString %>"
SelectCommand="SELECT Minotaur.dbo.Units.LinkNumber AS LinkNumber, RTAFleet.dbo.vehfile.vehicle AS UnitNumber FROM RTAFleet.dbo.vehfile INNER JOIN Minotaur.dbo.Units ON RTAFleet.dbo.vehfile.link_number = Minotaur.dbo.Units.LinkNumber AND Minotaur.dbo.Units.AcquisitionOrderID = #AcquisitionOrderID AND Minotaur.dbo.Units.SnapShotID = 1 AND Minotaur.dbo.Units.OldLinkNumber IS NULL">
<SelectParameters>
<asp:QueryStringParameter Name="AcquisitionOrderID" QueryStringField="orderID"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
here is the code behind:
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim LinkNoArray As String() = Request.QueryString("linkNumber").Split(",")
Dim SqlStr As String = "SELECT Vehicle = CASE WHEN ISNUMERIC(RTAFleet.dbo.vehfile.vehicle) = 1 AND RTAFleet.dbo.vehfile.vehicle IS NOT NULL THEN RTAFleet.dbo.vehfile.vehicle ELSE RTAFleet.dbo.vehfile.veh_xref_num END, RTAFleet.dbo.vehfile.link_number AS LinkNumber FROM RTAFleet.dbo.vehfile INNER JOIN Minotaur.dbo.Units ON RTAFleet.dbo.vehfile.link_number = Minotaur.dbo.Units.LinkNumber AND Minotaur.dbo.Units.SnapShotID = 1 WHERE "
For Each Str As String In LinkNoArray
SqlStr = SqlStr & " Minotaur.dbo.Units.LinkNumber = " & Trim(Str) & " OR"
Next
If Not Page.IsPostBack Then
SqlStr = Left(SqlStr, (SqlStr.Length - 2))
OldUnitsDataSource.SelectCommand = SqlStr
UnitMatchRepeater.DataBind()
End If
End Sub
Private Sub UnitMatchRepeater_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles UnitMatchRepeater.ItemCreated
If Not e.Item.ItemType = ListItemType.Item And Not e.Item.ItemType = ListItemType.AlternatingItem Then
Exit Sub
End If
Dim NewUnitsDDB As DropDownList = e.Item.FindControl("NewUnitsDropDownBox")
AddHandler NewUnitsDDB.SelectedIndexChanged, AddressOf NewUnitsDDB_SelectedIndexChanged
End Sub
Protected Sub NewUnitsDDB_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim linkNo As String = CType(sender, DropDownList).SelectedValue
Dim sqlStr As String = "UPDATE dbo.Units SET OldLinkNumber = #oldLinkNum WHERE LinkNumber = #newLinkNum"
Dim con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("minotaurSQLConnectionString").ConnectionString)
Dim cmd As SqlCommand = New SqlCommand(sqlStr, con)
cmd.Parameters.Add("#oldLinkNum", SqlDbType.Int).Value = CType(sender, DropDownList).Attributes("value")
cmd.Parameters.Add("#newLinkNum", SqlDbType.Int).Value = CInt(linkNo)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
dlistdatabinding()
End Sub
Private Sub dlistdatabinding()
For Each rep As RepeaterItem In UnitMatchRepeater.Items
Dim list As DropDownList = rep.FindControl("NewUnitsDropDownBox")
list.DataBind()
Next
End Sub
Please help to find out how to make it works.
thanks
Put your drop down list data binding code in the ItemDataBound event of your repeater. This is the event that fires every time it creates a "row" in your repeater. From there you can find the individual drop down list in the item.
The added benefit to this is that as each item is data bound, you could potentially change the contents of the drop down list based on the data you are working with.

Resources