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.
Related
I new on ASP.NET and I trying to do a web page based on VB code behind to set its behavior at frontend. And now I have list of asp Panel tags, each one has its own ID and it follows a numeric sequence. What I'm trying to do is to retrieve some of those IDs with a FOR loop to set them a CSS class. I thought it was gonna be something easy, but what a mistake!
Well, direct calls like this myPanel7.CssClass = "green" works. That's why naively I thought a simple code like this might works, but it does not.
For i=1 to x
xID = “myPanel” & i.ToString()
xID.CssClass = "green"
Next
So, I read some blogs and MS-docs and I understood that it’s necessary to create an object to inherit those properties, like ID and CSS. I tried this code and it works.
Dim xPanel As Panel
xID = "myPanel7"
xPanel = DirectCast(Page.FindControl(xID), Panel)
xPanel.CssClass = "green"
But when I tried to apply it on a FOR loop, it did not.
How can I solve this?, I need to get those IDs and apply one or another CSS rule.
Does anybody can, please, explain me what I'm doing wrong?
Why something like this does not work?
xID = "myPanel" & i.ToString()
Well, I leave you the structure of the code that I'm doing.
Thank you very much for your help.
Default.aspx
<asp:Panel ID="Container" CssClass="frm" runat="server">
<asp:Panel ID="Content" CssClass="txt" runat="server">
<asp:Panel ID="myPanel1" CssClass="white" runat="server"></asp:Panel>
<asp:Panel ID="myPanel2" CssClass="white" runat="server"></asp:Panel>
<asp:Panel ID="myPanel3" CssClass="white" runat="server"></asp:Panel>
<asp:Panel ID="myPanel4" CssClass="white" runat="server"></asp:Panel>
. . .
</asp:Panel>
</asp:Panel>
Default.aspx.vb
Partial Class _Default
Inherits System.Web.UI.Page
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xID As String
Dim xPanel As Panel
For i As Integer = 1 to xVar
xID = "myPanel" & i.ToString()
xPanel = DirectCast(Page.FindControl(xID), Panel)
xPanel.CssClass = "green"
Next
End Sub
End Class
My guess is you are working with Master Pages.
So you can either use FindControl in a parent Container like Container
xPanel = DirectCast(Container.FindControl(xID), Panel)
Or use FindControl on the ContentPlaceHolder of the Page containing the controls and find that first
Dim cph = CType(Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
And then in the loop
xPanel = DirectCast(cph.FindControl(xID), Panel)
I'm using the FindControl function to look for a control on the page. It seems super simple and straight forward on MSDN but I can't get it to find the control. The page I'm using has a MasterPageFile that prepends more to the id that I give the contorl in the aspx file. A simple example that isn't working:
aspx page
<%# Page Title="Inventory Control Test" Language="VB" AutoEventWireup="false" MasterPageFile="~/Site.master" CodeFile="Default2.aspx.vb" Inherits="Sales_ajaxTest_Default2" %>
<asp:Content ID="conHead" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="conBody" ContentPlaceHolderID="MainBody" Runat="Server">
<asp:Button ID="saveAllBtn" runat="server" Text="Save All" />
</asp:Content>
code behind
Partial Class Sales_ajaxTest_Default2
Inherits System.Web.UI.Page
Protected Sub saveAllBtn_Click(sender As Object, e As System.EventArgs) Handles saveAllBtn.Click
Dim myControl1 As Control = FindControl("ctl00_MainBody_saveAllBtn")
If (Not myControl1 Is Nothing) Then
MsgBox("Control ID is : " & myControl1.ID)
Else
'Response.Write("Control not found.....")
MsgBox("Control not found.....")
End If
End Sub
End Class
I get that msgbox isn't a web thing I'm just using it for this example.
If i use "saveAllBtn", which is the id given to the control, in the FindControl I get "control not found". If I try this, on a stand alone page without a masterpage it works fine.
If I inspect the element using chrome I find that the ID of the button has been changed to "ctl00_MainBody_saveAllBtn" but if I use that in the FindControl I still get "control not found"
When you use FindControl you would specify the "server ID" (what you named it) of the control, not the final rendered "client ID" of the control. ex:
Dim myControl as Control = MainBody.FindControl("saveAllBtn")
However, in your specific example, since you are in the saveAllBtn.Click event, the control you are looking for is actually the sender parameter (because you clicked on that button to trigger the event you are in) ex:
Dim myControl as Button = CType(sender, Button)
If you just want to find saveAllBtn control, wweicker's second method using CType(sender, Button) is the prefer one.
However, if you want to find other control by name, you cannot use just FindControl. You need to find the control recursively, because it is nested inside other controls.
Here is the helper method -
Protected Sub saveAllBtn_Click(sender As Object, e As EventArgs)
Dim button = TryCast(FindControlRecursive(Me.Page, "saveAllBtn"), Button)
End Sub
Public Shared Function FindControlRecursive(root As Control, id As String) As Control
If root.ID = id Then
Return root
End If
Return root.Controls.Cast(Of Control)().[Select](Function(c) FindControlRecursive(c, id)).FirstOrDefault(Function(c) c IsNot Nothing)
End Function
Note: My VB code might be a bite weird, because I wrote in C# and converted to VB using converter.
FindControl does not work recursively. You must start at one point (Me, for example), and if that is not the control your looking for, search the Controls collection of your starting point. And so forth.
I've got a asp.net gridview and inside of the grid view I have a check box at the header of the grid view like so:
<HeaderTemplate>
<asp:CheckBox Width="1px" ID="HeaderLevelCheckBox" AutoPostBack="true" OnCheckedChanged="SelectAllRows" runat="server" />
</HeaderTemplate>
This gives me a nice little check box at the top of the grid view...the event OnCheckedChanged calls a function called SelectAllRows that looks like this:
Public Sub SelectAllRows(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gr As GridViewRow = DirectCast(DirectCast(DirectCast(sender, CheckBox).Parent, DataControlFieldCell).Parent, GridViewRow)
Dim h As CheckBox = DirectCast(gr.FindControl("HeaderLevelCheckBox"), CheckBox)
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim cb As CheckBox = CType(Row.FindControl("chkSelector"), CheckBox)
cb.Checked = h.Checked
Next
End Sub
So if I click this header checkbox it checks all of the items in the gridview, and if I uncheck it, it unchecks all the items in the gridview. This works fine...but what doesnt seem to work is if the page loads up and I check the grid view header checkbox to true and it selects all the items in the gridview, then i click a button such as a DELETE button that calls some server side code. That code simply loops through the grid view and checks if the checkbox has been checked, if it is it calls code to delete an item. Something to this effect:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim cb As CheckBox = CType(Row.FindControl("chkSelector"), CheckBox)
Dim lID As Long = Convert.ToInt32(gvLineItems.DataKeys(Row.RowIndex).Value)
If cb IsNot Nothing AndAlso cb.Checked Then
'ok to delete
End If
Next
When I place a watch and debug on this it seems that the value cb is always false...
Even though it was set to true when I clicked the header checkbox...
What gives ???
The actual chkSelector in the grid view is for each row and it looks like this:
<ItemTemplate>
<asp:CheckBox ID="chkSelector" runat="server" onclick="ChangeRowColor(this)" />
</ItemTemplate>
Also I am already checking for postback..that is not the issue, remember chkSelector does not autopostback...
Thanks
I doubt, your gridview is rebinding on a Delete button click, because a click of the Delete button loads the page first where it will rebind and your checkbox's become unchecked again. I think you are binding your gridview some where in the page load event.
You have to do something like this
If(!Page.IsPostBack)
{
//Gridview Binding Code goes here....
}
Edit: Alternatively you can check/uncheck rows using javascript. It will save a round trip to the server side and resolve your current issue as well.
Here is complete code
<script language="javascript" type="text/javascript">
function SelectAll(spanChk,grdClientID) {
var IsChecked = spanChk.checked;
var Chk = spanChk;
Parent = document.getElementById(grdClientID);
var items = Parent.getElementsByTagName('input');
for(i=0;i<items.length;i++)
{
if(items[i].type=="checkbox")
{
items[i].checked=document.getElementById(spanChk).checked;
}
}
}
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkHeader" onclick="SelectAll('<%=chkHeader.ClientID %>, <%=yourGrid.ClientID %>') />
</HeaderTemplate>
here is the problem I am having with placeholder:
I have a repeater and within that repeater, I have an item template. Now this template is formatted with a couple of tables, but for this question I have removed them to make things easier to read:
<asp:Repeater ID="Repeater1" OnItemDataBound="R1_ItemDataBound" runat="server">
<ItemTemplate>
<asp:PlaceHolder ID="phAnswers" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:Repeater>
Then, on the event OnItemDataBound, I create a new placeholder, bind it to the existing on (phAnswers), however the placeholder is not updated with the radiobuttons/textboxs that are created:
Dim rdList As New RadioButtonList
Dim newRadio As New RadioButton
If (e.Item.ItemType = ListItemType.Item) Or _
(e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim tempPH As PlaceHolder
tempPH = e.Item.FindControl("phAnswers")
For x As Integer = 0 To (t_MC.Count - 1)
newRadio = New RadioButton
newRadio.ID = "Answer" + x.ToString
newRadio.Text = t_MC(x).Value
rdList.Controls.Add(newRadio)
Next
tempPH.Controls.Add(rdList)
Any ideas why phAnswers is not updated with the new tempPH placeholder?
Cheers
OnItemDataBound may be too late to add controls. Try it in OnItemCreated and see if that helps. It's a quick test - just change your repeater event declaration like this:
OnItemCreated="R1_ItemDataBound"
If this idea doesn't help, you can easily switch it back.
Edit - I just noticed something. To populate a RadioButtonList, you should use ListItems, like this:
ListItem item - new ListItem("your text", "your value");
rdList.Items.Add(item);
This is probably why your RadioButtonList did not appear, but lone radio buttons worked.
Try using a Panel instead of a PlaceHolder
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