I have a simple dropdownlist(ffg)...
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true" BackColor="LightSteelBlue" Font-Size="X-Small"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged1" Style="z-index: 102; left: 37px; position: absolute; top: 85px" Width="331px"
</asp:DropDownList>
which I bind data to usind the onpageload event...
DropDownList2.DataSource = td.DataSet
DropDownList2.DataSource = td
DropDownList2.DataTextField = td.Columns("Name").ColumnName.ToString
DropDownList2.DataValueField = td.Columns("VendorCode").ColumnName.ToString
DropDownList2.DataBind()
and an onleselectedindexchaged event where I try to retreive the new value like this...
Protected Sub DropDownList2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.TextChanged
Dim url As String = "sp_menu.aspx?sp=" & DropDownList2.SelectedValue
Session.Remove("sp")
Session("sp") = DropDownList2.SelectedValue
Session("spnm") = DropDownList2.SelectedItem.Text & " (" & DropDownList2.Text & ")"
Response.Redirect(url)
End Sub
But it always brings the first value no matter which one is clicked on the dropdownlist.
Please help!
Ok... a few things...
First
DropDownList2_TextChanged isn't wired to your DropDownList so I can't see how that event would ever fire unless you're doing the wireup in your codebehind
Second
You say this code here
DropDownList2.DataSource = td.DataSet
DropDownList2.DataSource = td
DropDownList2.DataTextField = td.Columns("Name").ColumnName.ToString
DropDownList2.DataValueField = td.Columns("VendorCode").ColumnName.ToString
DropDownList2.DataBind()
is in your PageLoad event. Have you wrapped it in an If Not IsPostBack,
because if not, then you'll rebind every time, and lose your previous selection.
When you're databinding in Page_Load, you're essentially also resetting the selecteditem.
You should wrap whatever bindingcode that exists in Page_Load inside an
if(!IsPostBack) block.
EDIT: ...or If Not IsPostBack Then ... End If in VB.NET
you can try to use
DropDownList2.SelectedItem.Value
instead of
DropDownList2.SelectedItem.Text
Related
Trying to Populate DropDownList when it is clicked (Asp.Net). I have a sample below but I can't get the DropDownList to stay expanded after it is loaded. Does anyone have a solution to load on demand from server other than using 3rd party controls?
JavaScript
<script type="text/javascript">
function LoadOnDemand(ddl) {
if (ddl != "") {
var control = document.getElementById(ddl.id);
__doPostBack(ddl.id, "LoadOnDemand");
}
}
function AfterLoadOnDemand(ddl) {
}
</script>
Markup
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="DynamicPanel" runat="server" Width="200">
</asp:Panel>
</div>
</form>
</body>
CodeBehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim target As String = Page.Request.Params.Get("__EVENTTARGET")
Dim eventarg As String = Page.Request.Params.Get("__EVENTARGUMENT")
Call CreateDynamicControls()
If IsPostBack Then
If target <> "" Then
If eventarg = "LoadOnDemand" Then
Dim ctrl As Control = FindControl(target)
If ctrl IsNot Nothing Then
If TypeOf ctrl Is DropDownList Then
'Note: values would be from a database or table query.
' and some other logic. Simplified here.
Dim ddl As DropDownList = CType(ctrl, DropDownList)
ddl.Items.Clear()
ddl.Items.Add("one")
ddl.Items.Add("two")
ddl.Items.Add("three")
'remove onfocus from this control so it doen't fire again
'if they click it immediatly after loading
ddl.Attributes.Add("onfocus", "AfterLoadOnDemand(this)")
End If
'reset the LoadOnDemand for all the other DropDownList controls
For Each notFocusedControl As Control In DynamicPanel.Controls
If TypeOf notFocusedControl Is DropDownList Then
Dim ddl As DropDownList = CType(notFocusedControl, DropDownList)
If ddl.ID <> target Then
ddl.Attributes.Add("onfocus", "LoadOnDemand(this)")
End If
End If
Next
End If
End If
End If
End If
End Sub
Protected Sub CreateDynamicControls()
For i As Integer = 0 To 2
Dim ddl As New DropDownList
ddl.ID = "DropDownList" & i
ddl.Width = 150
ddl.Items.Add("Browse me..")
ddl.Attributes.Add("onfocus", "LoadOnDemand(this)")
ddl.AutoPostBack = True
ddl.EnableViewState = True
DynamicPanel.Controls.Add(ddl)
DynamicPanel.Controls.Add(New LiteralControl("<br/><br/>"))
Next
End Sub
The only way I found out how to exand it is by emulation. Here is a link (ExpandSelect) that has a JavaScript function to do exactly that.
And here is another reference link.
I added the following (initialWidth parameter) to the .js file. This keeps the expanded dropdown from shrinking smaller then the initial width of the dropdown.
function ExpandSelect(select, maxOptionsVisible, initialWidth) {
//code - see file
select.style.zIndex = "1000000";
//Added this right after the zIndex
if (dropWidth < initialWidth) {
select.style.width = initialWidth + 'px';
select2.style.width = initialWidth + 'px';
}
//code - see file
}
I have a dynamic table being build on page_load.
I put the table inside an update panel so that I could add rows dynamically without a full page postback. Each row has 4 cells first 3 containing textboxes and the 4th cell being an image button that needs to delete the row.
However the image button to remove the row is posting back but not firing the event handler sub.
I set the table to a session variable for reloading on postbacks.
<%--Update Panel with Image Button to add row--%>
<asp:UpdatePanel ID="pnlHA" runat="server" UpdateMode="conditional" >
<ContentTemplate>
<asp:ImageButton ID="imgAddHA" AlternateText="Add Row" ImageUrl="../images/plus_orange.png" style="width:17px; height:17px; cursor: hand;" runat="server" />
<div style="height:100px; overflow:scroll; overflow-x:hidden;">
<span runat="server" id="spanTBL_HA" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
on page.init if the pnl page is in postback then it recreates the span
If pnlHA.Page.IsPostBack Then
spanTBL_HA.Controls.Clear()
spanTBL_HA.Controls.Add(CType(Session("tblHA"), Table))
End If
Image button being added to table cell
img = New ImageButton
Session("tblHA_Counter") = CInt(Session("tblHA_Counter")) + 1
img.AlternateText = "Delete Row"
img.Attributes.Add("style", "height: 10px; width: 10px; cursor: hand;")
img.ImageUrl = "../images/minus_red.png"
img.ID = "img_" & CInt(Session("tblHA_Counter")).ToString
AddHandler img.Click, AddressOf imgRemove_Click
img.Attributes.Add("runat", "server")
tc.Attributes.Add("style", "width:35px")
tc.Controls.Add(img)
Click Event
Protected Sub imgRemove_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
Dim img As ImageButton = CType(sender, ImageButton)
Dim delRow As TableRow = Nothing
Dim rowIndex As Integer = 0
For Each row As TableRow In CType(Session("tblHA"), Table).Rows
If CType(row.Cells(3).Controls(0), ImageButton).UniqueID = img.UniqueID Then
delRow = row
End If
Next
If delRow IsNot Nothing Then
CType(Session("tblHA"), Table).Rows.Remove(delRow)
End If
spanTBL_HA.Controls.Clear()
spanTBL_HA.Controls.Add(CType(Session("tblHA"), Table))
End Sub
Dynamic controls need to be recreated every time the page is created to allow ASP.NET to restore view state, postback data and event wireup to the dynamically created controls. So remember to recreate them on the postback as well.
Please check whether you are creating them on every post back.
How do I set ListView data through the codebehind instead of using the Bind() function in the Text attribute?
Right now I'm doing the following, but I'd like to have it retrieved and set in the codebehind. I'm using VB... Thanks!
<asp:Label ID="Date" runat="server" Text='<%# Bind("Date") %>'></asp:Label>
Edit:
Sorry, I'm binding the data in the following way with a DataTable.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ListView.DataSource = MyDataTable
ListView.DataBind()
End If
End Sub
use the ItemDataBound event.
Without seeing your code, I can tell you that a ListView has a DataSource property that you should just be able to set in your load code (and then do a DataBind()). I know I've done that before with a GridView.
Based on the info you have provided this is the best I can give you. You may want to put this snippet in the PreRender event for your ListView.
Label lblDate = (Label)ListView.FindControl("Date");
if(dataTable.Rows.Count > 0 && dataTables.Columns.Contains("Date"))
{
DataRow row = dataTable.Rows[0];
If(!DBNull.Equals(row["Date"])
{
lblDate.Text = row["Date"].ToString();
}
}
I am trying to have different options for different user roles. Here is my code:
Private Function GetApprovedBy() As String
If User.Identity.Name = "officer" Then
Return "Approved by Officer"
ElseIf User.Identity.Name = "manager" Then
Return "Approved by Manager"
Else
Return String.Empty
End If
End Function
Then inside my gridview templates I have:
<EditItemTemplate>
<asp:DropDownList ID="ApprovalEdit" runat="server">
<asp:ListItem>Rejected</asp:ListItem>
<asp:ListItem Text=<%= GetApprovedBy() %>></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
When I run the page I get
"Literal content ('<asp:ListItem Text=') is not allowed within a 'System.Web.UI.WebControls.ListItemCollection'."
Is there an alternative way of achieving this? Preferably without a DB.
Thanks in advance!!
Edit: I have also tried
<asp:ListItem><%= GetApprovedBy() %></asp:ListItem>
which failed with error 'Code blocks are not supported in this context'
careful with this: when binding (grid/list/repeater) use <%# %> and not <%= %>
here's an example of what #adrianos says:
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddl As DropDownList = CType(e.Row.FindControl("ApprovalEdit"), DropDownList)
' and then do the binding or add some items
End If
End Sub
(vb! aaagghhh my eyes T_T)
You could create a method that runs on the Gridview RowDataBound event.
In that method, search for your drop down list by id. If you find it, check your user type (manager / officer) and add the relevant listItems programmatically.
I believe that what you want is this:
<% ddlRooms.Items.Clear();
for (int i = 1; i <= 3; i++)
{
ddlRooms.Items.Add(new ListItem(i.ToString() , i.ToString()));
}
%>
<asp:DropDownList ID="ddlRoomsCountToBook" runat="server">
</asp:DropDownList>
This is the way that I found out to add dynamic elements in an dropdownlist on a view.
I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:
<asp:Button ID="btnShowDetails" runat="server" CausesValidation="false"
CommandName="Details" Text="Order Details"
onClientClick="window.open('PubsOrderDetails.aspx?OrderId=<%# Eval("order_id") %>',
'','scrollbars=yes,resizable=yes, width=350, height=550');"
Of course, what isn't working is the appending of the <%# Eval...%> section to set the query string variable.
Any suggestions? Or is there a far better way of achieving the same result?
I believe the way to do it is
onClientClick=<%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %>
I like #AviewAnew's suggestion, though you can also just write that from the code-behind by wiring up and event to the grid views ItemDataBound event. You'd then use the FindControl method on the event args you get to grab a reference to your button, and set the onclick attribute to your window.open statement.
Do this in the code-behind. Just use an event handler for gridview_RowDataBound. (My example uses a gridview with the id of "gvBoxes".
Private Sub gvBoxes_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBoxes.RowDataBound
Select Case e.Row.RowType
Case DataControlRowType.DataRow
Dim btn As Button = e.Row.FindControl("btnShowDetails")
btn.OnClientClick = "window.open('PubsOrderDetails.aspx?OrderId=" & DataItem.Eval("OrderId") & "','','scrollbars=yes,resizable=yes, width=350, height=550');"
End Select
End Sub