I am trying to retain a list of strings after a button press and have been using session variables. This is a snippet of the code:
.aspx page
<asp:Panel runat="server" ID="pnlAdd" >
<asp:DropDownList runat="server" ID="ddlOrder" >
<asp:ListItem Value="-1">Select an Order Type</asp:ListItem>
<asp:ListItem Value="1">hey there</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList runat="server" ID="ddlOrderStatus" >
<asp:ListItem Value="-1">Select an Order Status</asp:ListItem>
<asp:ListItem Value="1">another option</asp:ListItem>
</asp:DropDownList>
</asp:Panel>
<br />
<asp:Button runat="server" ID="btnAdd" Text="Add" />
.vb page
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim list As New List(Of String)
list = Session("flist")
list.Add(ddlOrder.SelectedItem.Text + " " + ddlOrderStatus.SelectedItem.Text)
Session("flist") = list
For i As Integer = 0 To 10
MsgBox(i.ToString + " " + list(i))
Next
MsgBox("Here")
End Sub
At the point that I assign the Session variable to list with list = Session("flist"), nothing will happen on the button click. If I remove that line, the rest of the button fires. Am I using the Session variable incorrectly? How can I achieve this correctly?
The list (of String) cannot be nothing before you are going to add elements into this list, So, change your code as follows:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim list As New List(Of String)
Dim objList As Object = Session.Item("flist")
If objList IsNot Nothing AndAlso TypeOf (objList) Is List(Of String) Then
list = CType(objList, List(Of String))
End If
list.Add(ddlOrder.SelectedItem.Text + " " + ddlOrderStatus.SelectedItem.Text)
Session("flist") = list
For i As Integer = 0 To list.Count - 1
MsgBox(i.ToString + " " + list(i))
Next
MsgBox("Here on end")
End Sub
Related
I need to get selected items on checkbox and set as string format like (value1,value2,value3) from the checkbox i selected
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim CheckRow As CheckBox = (TryCast(row.Cells(1).FindControl("chckSelector"), CheckBox))
If CheckRow.Checked Then
Dim scode As String = TryCast(row.Cells(2).FindControl("lblsstorecode"), Label).Text
lbltest.Text = 'this i want to get the value like this (value1,value2,value3) from checkbox that i selected
End If
End If
Next
Depending on why you are using the GridView control, you might me able to accomplish this easier by using a CheckBoxList instead. In Asp.net what you describe is accomplished very easily with a CheckBoxList as follows:
In .aspx:
<asp:CheckBoxList ID="Itemlst" runat="server" RepeatColumns="1">
<asp:ListItem Value="">Item 1</asp:ListItem>
<asp:ListItem Value="">Item 2</asp:ListItem>
<asp:ListItem Value="">Item 3</asp:ListItem>
</asp:CheckBoxList>
</br>
<asp:Button ID="Button1" runat="server" Text="Button" />
</br>
<asp:TextBox ID="TextBox1" runat="server" Width="400"></asp:TextBox>
Then in the code behind:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim selected = New List(Of ListItem)
Dim itemcount As Integer
Dim csvlist As String = ""
For Each item As ListItem In Itemlst.Items
If item.Selected Then selected.Add(item)
Next
itemcount = selected.Count
For i = 0 To itemcount - 1
csvlist = csvlist & selected(i).ToString & ","
Next
csvlist = Mid(csvlist, 1, Len(csvlist) - 1)
TextBox1.Text = csvlist
End Sub
The Windows Forms CheckedListBox would probably work similar if you are developing a desktop application.
This is the Design:::
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim i As Integer = 0
Dim j As Integer = 0
l1.Text = l2.Text
l2.Text = Val(l2.Text) + 10
i = Val(l1.Text)
j = Val(l2.Text)
MsgBox(i & " " & j)
While (i < j)
Dim b As Button = New Button()
b.ID = "b" + i.ToString()
b.Text = b.ID
Panel1.Controls.Add(b)
i = i + 1
End While
End Sub
This contains a button on click it should create 10 unique buttons..
i want to append all created buttons with existing buttons..
but the program is overriding instead of adding controls to the panel
help me.
I just tried this code. It doesn't override anything. It add the buttons to the very start of the page. If you want the buttons to appear after the button 'button 2' and labels then you should place the Panel, then it should be something like this
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
And if you want button to get added up along side the existing button and labels then instead of Panel either just use a place holder, or add style 'display:inline' to the Panel.
I think you want to add 10 dynamic controls on every button click. The problem you are facing right know is that on first click it adds 10 button controls, and on subsequent clicks it overrides the previous controls. Dynamic controls are created every time the page is requested so you have to create them on every request.
I write the following code to solve your query and it works:
// Aspx code
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
<asp:Button ID="Button2" runat="server" Text="Button" />
<asp:Label ID="l1" runat="server" Text="0"></asp:Label>
<asp:Label ID="l2" runat="server" Text="0"></asp:Label>
// Code BEhind
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim i As Integer = 0
Dim j As Integer = 0
l1.Text = l2.Text
l2.Text = Val(l2.Text) + 10
i = Val(l1.Text)
j = Val(l2.Text)
MsgBox(i & " " & j)
Dim lst As List(Of Integer) = New List(Of Integer) 'Create a list of integer type
lst.Add(i) 'Save value of i
lst.Add(j)
If Not Session("id_0") Is Nothing Then ' Will Check session for First Click exist or not
For k As Integer = 0 To DirectCast(Session("click"), Integer)
Dim mylst As List(Of Integer) = New List(Of Integer)
mylst = DirectCast(Session("id_" & k), List(Of Integer)) ' Assign Session Value to List
If Not mylst Is Nothing Then
WriteControls(mylst(0), mylst(1)) ' Call the function
End If
Next
End If
Session("id_" & DirectCast(Session("click"), Integer)) = lst ' Saves the entire list in Session
WriteControls(i, j) ' Function Call
End Sub
Private Sub WriteControls(i As Integer, j As Integer) ' Function to write button control
While (i < j)
Dim b As Button = New Button()
b.ID = "b" + i.ToString()
b.Text = b.ID
b.ViewStateMode = UI.ViewStateMode.Enabled
Panel1.Controls.Add(b)
i = i + 1
End While
Session("click") = DirectCast(Session("click"), Integer) + 1
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Session("click") = 0 ' Stores the no. of Clicks of the button
End If
End Sub
' Output
' If I press three times button then there will be 30 buttons
b0 b1 b2 b3 b4 ............................................... b29
20 30
I am trying to pass the selected items from a checkboxlist in asp.net (vs 2005/.net 2.0) as a concatenated string.
Currently my .aspx is
<asp:CheckBoxList id="checkbox1" AutoPostBack="False" AppendDataBoundItems="true" CellPadding="5" CellSpacing="5" RepeatColumns="1" RepeatDirection="Vertical" RepeatLayout="Flow" TextAlign="Right" runat="server">
<asp:ListItem Value="1">Carrots</asp:ListItem>
<asp:ListItem Value="2">Lettuce</asp:ListItem>
<asp:ListItem Value="3">Olives</asp:ListItem>
<asp:ListItem Value="4">Onions</asp:ListItem>
<asp:ListItem Value="5">Tomato</asp:ListItem>
<asp:ListItem Value="6">Pickles</asp:ListItem>
</asp:CheckBoxList>
And the .aspx.vb is (inside the Protected Sub for submit)
For Each li As ListItem In checkbox1.Items
If li.Selected = True Then
checkbox1.Text = checkbox1.Text + "," + li.Text
End If
Next
Which is written to the db via
checkbox1.Text = dv(0)("Salad").ToString()
When I select and save, I am currently getting an error
Server Error in '/' Application.
'checkbox1' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
Any thoughts on how to concatenate the selected checkbox items
For example, if some selects Carrots, Lettuce, and Tomato;
checkbox1 = 1,2,5
I don't think you are assigning to a variable like you describe you are returning.
string list = "";
For Each li As ListItem In chkQ4.Items
If li.Selected = True Then
list = list + "," + li.Text
End If
Next
is how you should write the line above.
In C# using linq, I would write
var list = checkbox1.Items
.Cast<ListItem>()
.Where(item => item.Selected == true)
.Select(item => item.Value);
var result = string.Join(",",list);
which I believe is the following in VB
Dim list = checkbox1.Items.Cast(Of ListItem)().Where(Function(item) item.Selected = True).[Select](Function(item) item.Value)
Dim result = String.Join(",", list.ToArray())
This is a little example
Markup:
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="1">Carrots</asp:ListItem>
<asp:ListItem Value="2">Apples</asp:ListItem>
<asp:ListItem Value="3">Lettuce</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Concatenate" /><br />
<asp:Button ID="Button2" runat="server" Text="Save" />
Codebehind:
Private Sub SaveItems(ByVal strItems As String)
Dim cn As New SqlConnection("user id=sa;password=abcd;database=BD_Test;server=SERVNAME")
Dim cmd As New SqlCommand("Insert into CheckItems values (#ItemId)", cn)
Dim cmdPar As New SqlParameter("#ItemId", SqlDbType.Char, 1)
If strItems.Split(",").Length > 0 Then
cmd.Parameters.Add(cmdPar)
Using cn
cn.Open()
Using cmd
''Split the existing selected values, store it in an array
''and iterate to get each element of it to save it in the DB
For Each strItem As String In strItems.Split(",")
cmd.Parameters("#ItemId").Value = strItem
cmd.ExecuteNonQuery()
Next
End Using
Me.Literal1.Text = "Items saved"
End Using
End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Literal1.Text = ""
For Each l As ListItem In Me.CheckBoxList1.Items
''Concatenate keeping the order of the items in your CheckboxList
If l.Selected Then
Me.Literal1.Text = Me.Literal1.Text & l.Value & ","
End If
Next
''Remove the final "," in case its at the end of the string
''to avoid db issues and selected items issues
If Right(Me.Literal1.Text, 1) = "," Then
Me.Literal1.Text = Left(Me.Literal1.Text, Me.Literal1.Text.Length - 1)
End If
''You can also save the items directly after concatenating
''Me.SaveItems(Me.Literal1.Text)
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.SaveItems(Me.Literal1.Text)
End Sub
The expected result is to have the selected values of the items on the page literal:
1,3
Hope this helps.
<%# Page Language="vb" MasterPageFile="~/4guys.master" %>
<%# Import Namespace="System.Web.Configuration" %>
<script runat="server">
Private Const VirtualImageRoot As String = "~/"
Private selectedFolderName As String
Private Sub Page_Init()
UserRoles.DataSource = Roles.GetAllRoles()
UserRoles.DataBind()
UserList.DataSource = Membership.GetAllUsers()
UserList.DataBind()
If IsPostBack Then
selectedFolderName = ""
Else
selectedFolderName = Request.QueryString("selectedFolderName")
End If
End Sub
Private Sub Page_Load()
'Interaction.MsgBox("Welcome");
If User.IsInRole("Administrator") Then
Else
Response.Redirect("~/homepage_aspx/homepage.aspx")
End If
If Not IsPostBack Then
PopulateTree()
End If
End Sub
Private Sub Page_PreRender()
If FolderTree.SelectedNode IsNot Nothing Then
DisplayAccessRules(FolderTree.SelectedValue)
SecurityInfoSection.Visible = True
End If
End Sub
Private Sub PopulateTree()
' Populate the tree based on the subfolders of the specified VirtualImageRoot
Dim rootFolder As New DirectoryInfo(Server.MapPath(VirtualImageRoot))
Dim root As TreeNode = AddNodeAndDescendents(rootFolder, Nothing)
FolderTree.Nodes.Add(root)
Try
FolderTree.SelectedNode.ImageUrl = "/Simple/i/target.gif"
Catch
End Try
End Sub
Private Function AddNodeAndDescendents(folder As DirectoryInfo, parentNode As TreeNode) As TreeNode
' Add the TreeNode, displaying the folder's name and storing the full path to the folder as the value...
Dim virtualFolderPath As String
If parentNode Is Nothing Then
virtualFolderPath = VirtualImageRoot
Else
virtualFolderPath = parentNode.Value + folder.Name + "/"
End If
Dim node As New TreeNode(folder.Name, virtualFolderPath)
node.Selected = (folder.Name = selectedFolderName)
' Recurse through this folder's subfolders
Dim subFolders As DirectoryInfo() = folder.GetDirectories()
For Each subFolder As DirectoryInfo In subFolders
If subFolder.Name <> "_controls" AndAlso subFolder.Name <> "App_Data" Then
Dim child As TreeNode = AddNodeAndDescendents(subFolder, node)
node.ChildNodes.Add(child)
End If
Next
Return node
' Return the new TreeNode
End Function
Protected Sub FolderTree_SelectedNodeChanged(sender As Object, e As EventArgs)
ActionDeny.Checked = True
ActionAllow.Checked = False
ApplyRole.Checked = True
ApplyUser.Checked = False
ApplyAllUsers.Checked = False
ApplyAnonUser.Checked = False
UserRoles.SelectedIndex = 0
UserList.SelectedIndex = 0
RuleCreationError.Visible = False
ResetFolderImageUrls(FolderTree.Nodes(0))
' Restore previously selected folder's ImageUrl.
FolderTree.SelectedNode.ImageUrl = "/Simple/i/target.gif"
' Set the newly selected folder's ImageUrl.
End Sub
Private Sub ResetFolderImageUrls(parentNode As TreeNode)
parentNode.ImageUrl = "/Simple/i/folder.gif"
' Recurse through this node's child nodes.
Dim nodes As TreeNodeCollection = parentNode.ChildNodes
For Each childNode As TreeNode In nodes
ResetFolderImageUrls(childNode)
Next
End Sub
Private Sub DisplayAccessRules(virtualFolderPath As String)
If Not virtualFolderPath.StartsWith(VirtualImageRoot) OrElse virtualFolderPath.IndexOf("..") >= 0 Then
Throw New ApplicationException("An attempt to access a folder outside of the website directory has been detected and blocked.")
End If
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim authorizationRules As AuthorizationRuleCollection = systemWeb.Authorization.Rules
RulesGrid.DataSource = authorizationRules
RulesGrid.DataBind()
TitleOne.InnerText = "Rules applied to " + virtualFolderPath
TitleTwo.InnerText = "Create new rule for " + virtualFolderPath
End Sub
Private Sub RowDataBound(sender As Object, e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rule As AuthorizationRule = DirectCast(e.Row.DataItem, AuthorizationRule)
If Not rule.ElementInformation.IsPresent Then
e.Row.Cells(3).Text = "Inherited from higher level"
e.Row.Cells(4).Text = "Inherited from higher level"
e.Row.CssClass = "odd"
End If
End If
End Sub
Private Function GetAction(rule As AuthorizationRule) As String
Return rule.Action.ToString()
End Function
Private Function GetRole(rule As AuthorizationRule) As String
Return rule.Roles.ToString()
End Function
Private Function GetUser(rule As AuthorizationRule) As String
Return rule.Users.ToString()
End Function
Private Sub DeleteRule(sender As Object, e As EventArgs)
Dim button As Button = DirectCast(sender, Button)
Dim item As GridViewRow = DirectCast(button.Parent.Parent, GridViewRow)
Dim virtualFolderPath As String = FolderTree.SelectedValue
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim section As AuthorizationSection = DirectCast(systemWeb.Sections("authorization"), AuthorizationSection)
section.Rules.RemoveAt(item.RowIndex)
config.Save()
End Sub
Private Sub MoveUp(sender As Object, e As EventArgs)
MoveRule(sender, e, "up")
End Sub
Private Sub MoveDown(sender As Object, e As EventArgs)
MoveRule(sender, e, "down")
End Sub
Private Sub MoveRule(sender As Object, e As EventArgs, upOrDown As String)
upOrDown = upOrDown.ToLower()
If upOrDown = "up" OrElse upOrDown = "down" Then
Dim button As Button = DirectCast(sender, Button)
Dim item As GridViewRow = DirectCast(button.Parent.Parent, GridViewRow)
Dim selectedIndex As Integer = item.RowIndex
If (selectedIndex > 0 AndAlso upOrDown = "up") OrElse (upOrDown = "down") Then
Dim virtualFolderPath As String = FolderTree.SelectedValue
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim section As AuthorizationSection = DirectCast(systemWeb.Sections("authorization"), AuthorizationSection)
' Pull the local rules out of the authorization section, deleting them from same:
Dim rulesArray As ArrayList = PullLocalRulesOutOfAuthorizationSection(section)
If upOrDown = "up" Then
LoadRulesInNewOrder(section, rulesArray, selectedIndex, upOrDown)
ElseIf upOrDown = "down" Then
If selectedIndex < rulesArray.Count - 1 Then
LoadRulesInNewOrder(section, rulesArray, selectedIndex, upOrDown)
Else
' DOWN button in last row was pressed. Load the rules array back in without resorting.
For x As Integer = 0 To rulesArray.Count - 1
section.Rules.Add(DirectCast(rulesArray(x), AuthorizationRule))
Next
End If
End If
config.Save()
End If
End If
End Sub
Private Sub LoadRulesInNewOrder(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
AddFirstGroupOfRules(section, rulesArray, selectedIndex, upOrDown)
AddTheTwoSwappedRules(section, rulesArray, selectedIndex, upOrDown)
AddFinalGroupOfRules(section, rulesArray, selectedIndex, upOrDown)
End Sub
Private Sub AddFirstGroupOfRules(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
Dim adj As Integer
If upOrDown = "up" Then
adj = 1
Else
adj = 0
End If
For x As Integer = 0 To selectedIndex - adj - 1
section.Rules.Add(DirectCast(rulesArray(x), AuthorizationRule))
Next
End Sub
Private Sub AddTheTwoSwappedRules(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
If upOrDown = "up" Then
section.Rules.Add(DirectCast(rulesArray(selectedIndex), AuthorizationRule))
section.Rules.Add(DirectCast(rulesArray(selectedIndex - 1), AuthorizationRule))
ElseIf upOrDown = "down" Then
section.Rules.Add(DirectCast(rulesArray(selectedIndex + 1), AuthorizationRule))
section.Rules.Add(DirectCast(rulesArray(selectedIndex), AuthorizationRule))
End If
End Sub
Private Sub AddFinalGroupOfRules(section As AuthorizationSection, rulesArray As ArrayList, selectedIndex As Integer, upOrDown As String)
Dim adj As Integer
If upOrDown = "up" Then
adj = 1
Else
adj = 2
End If
For x As Integer = selectedIndex + adj To rulesArray.Count - 1
section.Rules.Add(DirectCast(rulesArray(x), AuthorizationRule))
Next
End Sub
Private Function PullLocalRulesOutOfAuthorizationSection(section As AuthorizationSection) As ArrayList
' First load the local rules into an ArrayList.
Dim rulesArray As New ArrayList()
For Each rule As AuthorizationRule In section.Rules
If rule.ElementInformation.IsPresent Then
rulesArray.Add(rule)
End If
Next
' Next delete the rules from the section.
For Each rule As AuthorizationRule In rulesArray
section.Rules.Remove(rule)
Next
Return rulesArray
End Function
Private Sub CreateRule(sender As Object, e As EventArgs)
Dim newRule As AuthorizationRule
If ActionAllow.Checked Then
newRule = New AuthorizationRule(AuthorizationRuleAction.Allow)
Else
newRule = New AuthorizationRule(AuthorizationRuleAction.Deny)
End If
If ApplyRole.Checked AndAlso UserRoles.SelectedIndex > 0 Then
newRule.Roles.Add(UserRoles.Text)
AddRule(newRule)
ElseIf ApplyUser.Checked AndAlso UserList.SelectedIndex > 0 Then
newRule.Users.Add(UserList.Text)
AddRule(newRule)
ElseIf ApplyAllUsers.Checked Then
newRule.Users.Add("*")
AddRule(newRule)
ElseIf ApplyAnonUser.Checked Then
newRule.Users.Add("?")
AddRule(newRule)
End If
End Sub
Private Sub AddRule(newRule As AuthorizationRule)
Dim virtualFolderPath As String = FolderTree.SelectedValue
Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(virtualFolderPath)
Dim systemWeb As SystemWebSectionGroup = DirectCast(config.GetSectionGroup("system.web"), SystemWebSectionGroup)
Dim section As AuthorizationSection = DirectCast(systemWeb.Sections("authorization"), AuthorizationSection)
section.Rules.Add(newRule)
Try
config.Save()
RuleCreationError.Visible = False
Catch ex As Exception
RuleCreationError.Visible = True
RuleCreationError.Text = "<div class=""alert""><br />An error occurred and the rule was not added. I saw this happen during testing when I attempted to create a rule that the ASP.NET infrastructure realized was redundant. Specifically, I had the rule <i>DENY ALL USERS</i> in one folder, then attempted to add the same rule in a subfolder, which caused ASP.NET to throw an exception.<br /><br />Here's the error message that was thrown just now:<br /><br /><i>" + ex.Message + "</i></div>"
End Try
End Sub
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="c" Runat="Server">
<!-- #include file="_nav.aspx -->
<table class="webparts">
<tr>
<th>Website Access Rules</th>
</tr>
<tr>
<td class="details" valign="top">
<p>
Use this page to manage access rules for your Web site. Rules are applied to folders, thus providing robust folder-level security enforced by the ASP.NET infrastructure. Rules are persisted as XML in each folder's Web.config file. <i>Page-level security and inner-page security are not handled using this tool — they are handled using specialized code that is available to the Web Developers.</i>
</p>
<table>
<tr>
<td valign="top" style="padding-right: 30px;">
<div class="treeview">
<asp:TreeView runat="server" ID="FolderTree"
OnSelectedNodeChanged="FolderTree_SelectedNodeChanged">
<RootNodeStyle ImageUrl="/Simple/i/folder.gif" />
<ParentNodeStyle ImageUrl="/Simple/i/folder.gif" />
<LeafNodeStyle ImageUrl="/Simple/i/folder.gif" />
<SelectedNodeStyle Font-Underline="true" ForeColor="#A21818" />
</asp:TreeView>
</div>
</td>
<td valign="top" style="padding-left: 30px; border-left: 1px solid #999;">
<asp:Panel runat="server" ID="SecurityInfoSection" Visible="false">
<h2 runat="server" id="TitleOne" class="alert"></h2>
<p>
Rules are applied in order. The first rule that matches applies, and the permission in each rule overrides the permissions in all following rules. Use the Move Up and Move Down buttons to change the order of the selected rule. Rules that appear dimmed are inherited from the parent and cannot be changed at this level.
</p>
<asp:GridView runat="server" ID="RulesGrid" AutoGenerateColumns="false"
CssClass="list" GridLines="none"
OnRowDataBound="RowDataBound"
>
<Columns>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<!--response.write(GetAction((AuthorizationRule)Container.DataItem))-->
**<%#GetAction((AuthorizationRule), Container.DataItem)%>**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roles">
<ItemTemplate>
<!-- response.write(GetRole((AuthorizationRule)Container.DataItem))-->
**<%# GetRole((AuthorizationRule),Container.DataItem) %>**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User">
<ItemTemplate>
<!-- response.write(GetUser((AuthorizationRule)Container.DataItem))-->
**<%#GetUser((AuthorizationRule), Container.DataItem)%>**
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Rule">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Delete Rule" CommandArgument="<%# (AuthorizationRule)Container.DataItem %>" OnClick="DeleteRule" OnClientClick="return confirm('Click OK to delete this rule.')" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Move Rule">
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text=" Up " CommandArgument="<%# (AuthorizationRule)Container.DataItem %>" OnClick="MoveUp" />
<asp:Button ID="Button3" runat="server" Text="Down" CommandArgument="<%# (AuthorizationRule)Container.DataItem %>" OnClick="MoveDown" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<hr />
<h2 runat="server" id="TitleTwo" class="alert"></h2>
<b>Action:</b>
<asp:RadioButton runat="server" ID="ActionDeny" GroupName="action"
Text="Deny" Checked="true" />
<asp:RadioButton runat="server" ID="ActionAllow" GroupName="action"
Text="Allow" />
<br /><br />
<b>Rule applies to:</b>
<br />
<asp:RadioButton runat="server" ID="ApplyRole" GroupName="applyto"
Text="This Role:" Checked="true" />
<asp:DropDownList ID="UserRoles" runat="server" AppendDataBoundItems="true">
<asp:ListItem>Select Role</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RadioButton runat="server" ID="ApplyUser" GroupName="applyto"
Text="This User:" />
<asp:DropDownList ID="UserList" runat="server" AppendDataBoundItems="true">
<asp:ListItem>Select User</asp:ListItem>
</asp:DropDownList>
<br />
<asp:RadioButton runat="server" ID="ApplyAllUsers" GroupName="applyto"
Text="All Users (*)" />
<br />
<asp:RadioButton runat="server" ID="ApplyAnonUser" GroupName="applyto"
Text="Anonymous Users (?)" />
<br /><br />
<asp:Button ID="Button4" runat="server" Text="Create Rule" OnClick="CreateRule"
OnClientClick="return confirm('Click OK to create this rule.');" />
<asp:Literal runat="server" ID="RuleCreationError"></asp:Literal>
</asp:Panel>
</td>
</tr>
</table>
</td>
</tr>
</table>
</asp:Content>
'AuthorizationRule' is a type and cannot be used as an expression.
errors are bold.
In some places of your markup you have an unnecessary , (line no. 352, 358 and 364)
stuff like
<%#GetAction((AuthorizationRule), Container.DataItem)%>
I think, should be
<%#GetAction(DirectCast(Container.DataItem, AuthorizationRule))%>
similarly
<%#GetRole(CType(Container.DataItem, AuthorizationRule))%>
and
<%#GetUser(DirectCast(Container.DataItem, AuthorizationRule))%>
Also use this replacing what you have
<asp:Button ID="Button1" runat="server" Text="Delete Rule" CommandArgument='<%# DirectCast(Container.DataItem, AuthorizationRule) %>' OnClick="DeleteRule" OnClientClick="return confirm('Click OK to delete this rule.')" />
and
<asp:Button ID="Button2" runat="server" Text=" Up " CommandArgument='<%# DirectCast(Container.DataItem, AuthorizationRule) %>' OnClick="MoveUp" />
<asp:Button ID="Button3" runat="server" Text="Down" CommandArgument='<%# DirectCast(Container.DataItem, AuthorizationRule) %>' OnClick="MoveDown" />
I have a simple usercontrol, with a datalist, and checkboxes inside.
<asp:DataList ID="DataListDroits" runat="server" DataKeyField="droit_id" DataSourceID="SqlDroits">
<ItemTemplate>
<asp:HiddenField ID="HiddenFieldDroitID" runat="server" Value='<%# Eval("droit_id") %>' />
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' />
</ItemTemplate>
</asp:DataList>
I check them using code behind in the usercontrol :
Public Sub CheckRole(ByVal role As Integer)
For Each dliOrganisme As DataListItem In Me.DataListOrganismes.Items
Dim DataListDroits As DataList = dliOrganisme.FindControl("DataListDroits")
If DataListDroits IsNot Nothing Then
For Each dliDroit As DataListItem In DataListDroits.Items
If role = CInt(CType(dliDroit.FindControl("HiddenFieldDroitID"), HiddenField).Value) Then
Dim CheckBoxDroit As CheckBox = dliDroit.FindControl("CheckBoxDroit")
CheckBoxDroit.Checked = True
End If
Next ' DataListDroits
End If
Next ' DataListItem
End Sub
And in the page_load of the calling webform :
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
Dim rolesCoches As New List(Of Integer)
Dim cmdRoles As New SqlCommand("SELECT droit_id FROM o_droit_rubrique WHERE rubrique_id = #rubrique", conn)
cmdRoles.Parameters.AddWithValue("rubrique", Request.QueryString("rid"))
Dim rdrRoles As SqlDataReader = cmdRoles.ExecuteReader
While rdrRoles.Read
CheckBoxesRoles1.CheckRole(rdrRoles("droit_id"))
End While
rdrRoles.Close()
... and yet, they are not checked.
But if I do this :
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
Dim CheckBoxesRoles1 As ASP.organisme_checkboxesroles_ascx = Me.FormViewRubrique.FindControl("CheckBoxesRoles1")
If CheckBoxesRoles1 IsNot Nothing Then
For Each role As Integer In CheckBoxesRoles1.CheckedRoles
Response.Write("role : " & role & "<br>")
Next
End If
End Sub
I tells me they are...
I'm going mad here ! Why does it tells me they are checked while they obviously are not ?
Well... for one thing, you aren't checking if your checkboxes are checked, all you're doing is outputting the value of "role". What exactly are you expecting here?
Two suggestions:
1) Set the Checked property of your CheckBox in the aspx like so:
<asp:CheckBox ID="CheckBoxDroit" runat="server" Text='<%# Eval("droit_label") %>' Checked='<%# (Eval("droit_id") > 0).ToString()' />
2) Set the property in OnItemDataBound in code-behind
One of two things is happening: Either the code you expect to be executing is not really executing (ie, is your if block ever true? Is the control not being found? Try a breakpoint), OR you are doing it at the wrong time -- after the page has already been rendered.