Why doesn't User.IsInRole work in this context? - c#

...I want to Show the 'delete' button when user is an admin, and show the 'add item' button when user is a contributor:
<!-- More code above -->
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton CSSClass="TableRightLink" ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Delete"
Visible=<%# User.IsInRole(#"DOMAIN\CMDB_ADMIN") %>
Text="Delete"
OnClientClick="return confirm('Are you certain you want to delete this item?');"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle VerticalAlign="Top" />
<HeaderStyle ForeColor="White" CssClass="TableHeader" BackColor="SteelBlue" />
</asp:GridView>
<asp:table width="100%" runat="server" CSSclass="PromptTable" Visible=<%# User.IsInRole(#"DOMAIN\CMDB_CONTRIBUTE") %> >
<asp:tablerow><asp:tablecell HorizontalAlign=Center>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="AddConfigItem.aspx" ForeColor="LightCyan">Add Item</asp:HyperLink>
</asp:tablecell></asp:tablerow></asp:table>
The Delete button 'visible' attribute works fine. But, the "add item' hyperlink doesn't. It always shows.
View-source tells me that %# User.IsInRole(#"DOMAIN\CMDB_CONTRIBUTE") %> isn't evaluating to anything. Any idea why this is?

Try setting it in code behind, instead of in mark up, in Page_Load. Assuming the id is promptTable (it wasn't given in your example), just add:
promptTable.Visible = User.IsInRole(#"DOMAIN\CMDB_CONTRIBUTE");
Presumably this needs to be done regardless of whether it is a postback or not.
FWIW, #Keltex is right about the control not being databound so <%# %> won't work. Unfortunately, the <%= %> syntax won't either because it always returns a string and you need a boolean value there. I couldn't find any other syntax that would work in this case. You could probably do this by turing off display using javascript, but I suspect that you don't want the table to be rendered to the page if not in the correct group (as opposed to just being hidden or removed from the DOM once on the client). Doing it in the code behind, I think is the right way to go about it.

Try:
Visible='<%= User.IsInRole(#"DOMAIN\CMDB_CONTRIBUTE") %>'
The asp:table doesn't appear to be databound.

Related

Pass parameter from Gridview column to Javascript

I need to pass an argument (which comes from my database) from a radgrid view column to my javascript (which opens a dialog box window). However, I can't put the "bind("Id")" as a parameter from where I call the javascript as href.
In simpler words, I am looking for a way to pass <% Bind("Id")%> to the javascript, OpenMyWindow, call instead of the hardcoded, 111, right now.
<telerik:GridTemplateColumn UniqueName="Meet" DataField="Subject" HeaderText="Meet">
<ItemTemplate>
<div style="text-align: center">
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%# Bind("Subject") %>' href="javascript: OpenMyWindow(111);" Width="30%">
</asp:LinkButton>
</div>
</ItemTemplate>
</telerik:GridTemplateColumn>
When I try "OnClick" instead of "href", my popup dialog box closes instantly and doesn't stay opened.
Try using "OnClientClick" and return false from your javascript method to prevent post back.
Alternatively. You could use a method passing in the DataIten. Then output an anchor tag created anyway you like:
<%# formatOpener(Container.DataItem) %>
With code behind of:
protected string formatOpener(object item)
{
ObjectType myObj = (ObjectType)item;
return String.Format("<a href=\"javascript:OpenMyWindow({0});\" width=\"30%\"/>{1}</a>", myObj.ID, myObj.subject);
}
I think you don't need a LinkButton, you could achieve it with an asp:HyperLink (which renders as a a tag):
<asp:HyperLink ID="HyperLink1" runat="server" Text='<%# Eval("Subject") %>' NavigateUrl='<%# "javascript: OpenMyWindow(" + Eval("ID").ToString() + ");" %>'></asp:HyperLink>
Also, don't use Bind if you don't need it, for displaying purposes always use Eval.
User HyperLink control instead and try setting the NavigateUrl property of the HyperLink this way:
<asp:HyperLink ID="hlLink" runat="server" Text='<%# Bind("Subject") %>' NavigateUrl='<%#Eval("Id", "javascript: OpenMyWindow({0});")%>'>
hope it helps./.
I finally figured out and solved this issue. Actually, somebody told me on the other post that, CommandArgument is completely a server-side property and doesn't render any html attribute. So I can't change any button's attribute and fire click on it. I finally made "Id" come through the code behind and made it work.
aspx code
<telerik:GridButtonColumn UniqueName="Subject" DataTextField="Subject" HeaderText="Meeting">
<HeaderStyle Width="30%" />
<ItemStyle HorizontalAlign="Center" />
</telerik:GridButtonColumn>
Code Behind
var subjectLink = meetingRow["Subject"].Controls[0] as LinkButton;
subjectLink.Attributes.Add("onClick", "javascript: return OpenMyWindow('" + meetingId + "')");

Visibility of an ASP.Net button which depends if a file exists in database

I have a gridview which has a few rows (each with a unique rowId), and each line has a FileUpload control, now everything works okay with FileUpload.
(my uploaded file database image can be seen below)
I have the download button, which also works okay, however I want to make this button invisible if no file exists for the corresponding row.
Nothing proper comes to my mind.
My button and FileUpload control:
<asp:TemplateField HeaderText="BatchList">
<EditItemTemplate>
<asp:ImageButton ID="ibt_Download" runat="server" src="Images/Download.png" CommandName="Download" CommandArgument='<%# Container.DataItemIndex %>' ></asp:ImageButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UploadBatchList">
<HeaderTemplate>
<asp:Label ID="lbl_Header" ToolTip="Upload Batch List" runat="server" Text="UBL"></asp:Label>
</HeaderTemplate>
<EditItemTemplate>
<asp:FileUpload ID="fu_UploadBatchList" runat="server" />
<asp:Button ID="btn_Upload" runat="server" Text="Upload" OnClick="btn_Upload_Click" />
</EditItemTemplate>
</asp:TemplateField>
This is how it looks on my gridView
When gridview is first created the green dots must not be visible if a file has been uploaded before.
My file database:
You can check some property of the data item (DocName in your case) if it contains a value (it might not work when copy-pasted, I'm a little bit improvising):
<asp:Button ID="btn_Upload" runat="server"
Text="Upload"
Visible='<% DataBinder.Eval(Container.DataItem, "DocName") == null %>
OnClick="btn_Upload_Click" />
Or you can create a function that will evaluate the visibility. See Mastering ASP.NET DataBinding for more.

Change GridView's "Checked Out" column from a button to a label based on whether cardNumber is null or not

NOTE: I'm a beginner web developer, somewhat familiar with PHP. I've been curious about ASP.NET and wanted to give it a go.
Now, I'm attempting to little library application that displays a table like the following:
Title - Author - Status
The Eye of the World - Robert Jordan - Checked Out
The Great Hunt - Robert Jordan - Check Out
The Dragon Reborn - Robert Jordan - Check Out
I have created a DataSet, and a TableAdapter that performs the following query:
SELECT books.SerialNumber, books.Title, books.Author, CheckedOut.cardNumber
FROM books LEFT OUTER JOIN
CheckedOut ON books.SerialNumber = CheckedOut.SerialNumber
I do this so that I can get either NULL or the cardNumber for use below.
Here is the current state of my main page:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Browse.aspx.cs" Inherits="_Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="SerialNumber,cardNumber" DataSourceID="ObjectDataSource1"
OnRowDataBound="browseMethod"
AllowPaging="True" onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="SerialNumber" HeaderText="SerialNumber"
InsertVisible="False" ReadOnly="True" SortExpression="SerialNumber"
Visible="False" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Author" HeaderText="Author"
SortExpression="Author" />
<asp:BoundField DataField="cardNumber" HeaderText="cardNumber"
SortExpression="cardNumber" Visible="False" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Button ID="Button1" runat="server"
CommandArgument='<%# Eval("cardNumber") %>'
Text="Check Out" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetLibraryBooks"
TypeName="DataSet1TableAdapters.DataTable1TableAdapter">
</asp:ObjectDataSource>
</asp:Content>
I want to be able to change the "Check Out" button to a label ("Checked Out") when the "cardNumber" value for that row is NULL. Also, how can I create an event when each button is called, and grab the correct SerialNumber?
You can create another control label and sets its visibity to false.You have already defied command argument for the button.Give a command name too .
<asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("cardNumber") %>' CommandName="CheckOut" Text="Check Out" />
In the gridview_rowCommand callback check for the command Name and do the operations.Set the visibility of button to false there and label to true.ANother option woulb be to enable/disable button as discussed in answer above with disabled style being made in a way such that it looks like a label.For grid view command argument refer the follwoing link :-
http://msdn.microsoft.com/en-us/library/bb907626.aspx
In the browseMethod, which will be called for every row in the grid, when the grid is getting populated. So you can make the button enabled or disabled based on the condition..
You can get the button using row.FindControl by button name "Button1" cast it into button and call button.Enabled = true or false.. based on cc number..
I hope this should direct you in the right path...

Asp.net controls are not accessible in code behind

I have a project that was previously built by someone else. When I try to add a new control to the page, I can't access it in the code behind. When I try to access it there's an error message that the Control is not defined in the current context.
<%# Page Language="C#" MasterPageFile="~/HRMS.Master" AutoEventWireup="true" CodeBehind="manageEmployee.aspx.cs" Inherits="HRMS.manageEmployee" Title="Untitled Page" %>
<%# Register Assembly="eWorld.UI" Namespace="eWorld.UI" TagPrefix="ew" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script type="text/javascript">
document.getElementById("employee").setAttribute("class", "selected");
</script>
<!--OPEN CONTENT DIV-->
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<!-- Only this area is updated on PostBack -->
<div class="manage_employ">
<ul>
<li style="margin-top:10px; margin-bottom:15px"><input type="image" src="images/img_manageEmployee01.png"/></li>
</ul>
<ul>
<li>First name</li>
<li><asp:TextBox runat="server" class="text_input" id="txtFirstName"/></li>
<asp:RequiredFieldValidator ID="validatorFirstName" runat="server" ErrorMessage="*" ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
<li>Last name</li>
<li><asp:TextBox runat="server" class="text_input" id="txtLastName"/></li>
<asp:RequiredFieldValidator ID="validatorLastname" runat="server" ErrorMessage="*" ControlToValidate="txtLastName"></asp:RequiredFieldValidator>
</ul>
<ul>
<li>CNIC</li>
<li><asp:TextBox runat="server" class="text_input" id="txtCNIC"/></li>
<asp:RequiredFieldValidator ID="validatorCNIC" runat="server" ErrorMessage="*" ControlToValidate="txtCNIC"></asp:RequiredFieldValidator>
<li>Blood Group</li>
<li><asp:DropDownList runat="server" class="text_input" id="ddlBloodGroup">
<asp:ListItem>A+</asp:ListItem>
<asp:ListItem>B+</asp:ListItem>
<asp:ListItem>AB+</asp:ListItem>
<asp:ListItem>A-</asp:ListItem>
<asp:ListItem>B-</asp:ListItem>
<asp:ListItem>AB-</asp:ListItem>
<asp:ListItem>O+</asp:ListItem>
<asp:ListItem>O-</asp:ListItem>
</asp:DropDownList>
</li>
</ul>
<ul>
<li>Mobile</li>
<li><asp:TextBox runat="server" class="text_input" id="txtMobile"/></li>
<asp:RequiredFieldValidator ID="validatorMobile" runat="server" ErrorMessage="*" ControlToValidate="txtMobile"></asp:RequiredFieldValidator>
<li>Phone</li>
<li><asp:TextBox runat="server" class="text_input" id="txtPhone"/></li>
</ul>
<ul>
</ul>
<ul>
<li>E-Mail</li>
<li><asp:TextBox runat="server" class="text_input" id="txtEmail"/></li>
<asp:RegularExpressionValidator ID="valEmail" ControlToValidate="txtEmail" runat="server" ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<li>Maritial Status</li>
<li>
<asp:RadioButton ID="rbtnMarried" AutoPostBack="true" runat="server" oncheckedchanged="rbtnMarried_CheckedChanged"/>Married
<asp:RadioButton ID="rbtnUnmarried" AutoPostBack="true" runat="server"
oncheckedchanged="rbtnUnmarried_CheckedChanged"/>Unmarried
</li>
</ContentTemplate>
</asp:UpdatePanel>
</ul>
<ul>
<li>Permanant Address</li>
<li><asp:TextBox runat="server" class="text_input" id="txtPermanantAddress"/></li>
<asp:RequiredFieldValidator ID="validatorPAddress" runat="server" ErrorMessage="*" ControlToValidate="txtPermanantAddress"></asp:RequiredFieldValidator>
<li>Temporary Address</li>
<li><asp:TextBox runat="server" class="text_input" id="txtTemporaryAddress"/></li>
<asp:RequiredFieldValidator ID="validatorTAddress" runat="server" ErrorMessage="*" ControlToValidate="txtTemporaryAddress"></asp:RequiredFieldValidator>
</ul>
<ul>
<li>Salary</li>
<li><asp:TextBox runat="server" class="text_input" id="txtSalary"/></li>
<asp:RequiredFieldValidator ID="validatorSalary" runat="server" ErrorMessage="*" ControlToValidate="txtSalary"></asp:RequiredFieldValidator>
<li>Joining Date</li>
<li>
<%--<ew:calendarpopup ID="calJoiningDate" runat="server"></ew:calendarpopup>--%>
<asp:TextBox ID="CalJoiningDate1" runat="server" CssClass="text_input"></asp:TextBox>
<cc1:CalendarExtender ID="CalJoiningDate1_CalendarExtender" runat="server"
Enabled="True" TargetControlID="CalJoiningDate1">
</cc1:CalendarExtender>
</li>
</ul>
<ul>
<li>Job Area</li>
<li><asp:DropDownList runat="server" class="text_input" id="ddlJobArea"/></li>
<li>Desigantion</li>
<li><asp:DropDownList runat="server" class="text_input" id="ddlDesignation"/></li>
</ul>
<asp:UpdatePanel ID="updatePnl" runat="server">
<ContentTemplate>
<div>
<ul>
<li style="margin-top:20px; margin-bottom:15px"><input type="image" src="images/img_jobHistory.png" /></li>
</ul>
<ul>
<li>Company</li>
<%--<asp:DropDownList runat="server" class="text_input" id="ddlCompany"
onselectedindexchanged="ddlCompany_SelectedIndexChanged"/>--%>
<li><asp:TextBox ID="CompanyNames" runat="server" CssClass="text_input"></asp:TextBox>
<cc1:AutoCompleteExtender ID="CompanyNames_AutoCompleteExtender" runat="server"
DelimiterCharacters="" Enabled="True" ServicePath="getCompanies.asmx" ServiceMethod="getCompaniesMethod" MinimumPrefixLength="1"
TargetControlID="CompanyNames" UseContextKey="True">
</cc1:AutoCompleteExtender>
<li>Job Duration</li>
<li>
<asp:TextBox ID="txtJobDuration" runat="server" class="text_input" />
</li>
<asp:RequiredFieldValidator ID="validatorJobDuration" runat="server"
ControlToValidate="txtJobDuration" ErrorMessage="*"
ValidationGroup="jobHistory"></asp:RequiredFieldValidator>
</li>
</ul>
<ul>
<li>Job Area</li>
<li><asp:DropDownList runat="server" class="text_input" id="ddlJobHistJobArea"/></li>
<li>Designation</li>
<li><asp:DropDownList runat="server" class="text_input" id="ddlJobHistoryDesignation"/></li>
</ul>
<ul>
<li>Last Drawn Salary</li>
<li><asp:TextBox runat="server" class="text_input" id="txtLastDrawnSalary"/>
</li>
<asp:RequiredFieldValidator ID="validatorLastDrawnSalary" runat="server" ValidationGroup="jobHistory" ErrorMessage="*" ControlToValidate="txtLastDrawnSalary"></asp:RequiredFieldValidator>
</ul>
<ul>
<li style="margin-left:160px">
<asp:ImageButton src="images/btn_Add.png" runat="server" ID="btnAddJobHistory" onclick="btnAddJobHistory_Click" CausesValidation="True" ValidationGroup="jobHistory"/>
<asp:ImageButton src="images/btnReset.png" runat="server" ID="btnResetJH" CausesValidation="False" onclick="btnResetJH_Click"/>
</li>
</ul>
<ul style="margin-left:30px">
<asp:GridView ID="grdJobHistory" runat="server" AutoGenerateColumns="False" Width="798px"
AllowPaging="True"
onpageindexchanging="grdJobHistory_PageIndexChanging"
onrowcommand="grdJobHistory_RowCommand"
onrowdeleting="grdJobHistory_RowDeleting"
onrowediting="grdJobHistory_RowEditing" Font-Bold="True"
Font-Names="Calibri" Font-Size="Medium" ForeColor="White" PageSize="5">
<Columns>
<asp:BoundField DataField="EmployeeExperianceId"
HeaderText="EmployeeExperianceId" />
<asp:BoundField HeaderText="Company" DataField="CompanyName" ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField DataField="JobAreaName" HeaderText="Job Area" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Smaller" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Designation" DataField="DesignationName"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Experiance Duration" DataField="ExperianceDuration"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Salary" DataField="LastDrawnSalary" ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:TemplateField AccessibleHeaderText="Edit" HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" ImageUrl="images/updateIcon.png" CausesValidation="False" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeExperianceId") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="Delete" HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="images/deleteIcon.png" CausesValidation="False" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeExperianceId") %>' OnClientClick="return confirm('Are you sure you want to delete this record...');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#5D92B9" BorderStyle="None" />
<AlternatingRowStyle BackColor="#AAAAAA" />
</asp:GridView>
</ul>
</div>
<div>
<ul>
<li style="margin-top:20px; margin-bottom:15px"><input type="image" src="images/img_skillDetail.png" /></li>
</ul>
<ul>
<li>Skill</li>
<!--<li><asp:DropDownList runat="server" class="text_input" id="ddlSkill"/></li>-->
<li>
<asp:TextBox ID="SkillAutoComplete" runat="server" CssClass="text_input"></asp:TextBox>
<cc1:AutoCompleteExtender ID="SkillAutoComplete_AutoCompleteExtender"
runat="server" DelimiterCharacters="" Enabled="True" ServicePath="getSkills.asmx" ServiceMethod="getAllSkills" MinimumPrefixLength="1"
TargetControlID="SkillAutoComplete">
</cc1:AutoCompleteExtender>
</li>
<li>Skill Detail</li>
<li><asp:TextBox runat="server" class="text_input" id="txtSkillDetail"/></li>
<asp:RequiredFieldValidator ID="validatorSkillDetail" runat="server" ValidationGroup="skill" ErrorMessage="*" ControlToValidate="txtSkillDetail"></asp:RequiredFieldValidator>
</ul>
<ul>
<li style="margin-left:160px">
<asp:ImageButton src="images/btn_Add.png" runat="server" ID="btnAddSkill" CausesValidation="True" ValidationGroup="skill" onclick="btnAddSkill_Click"/>
<asp:ImageButton src="images/btnReset.png" runat="server" ID="btnResetSkill" CausesValidation="False" onclick="btnResetSkill_Click"/>
</li>
</ul>
<ul style="margin-left:30px">
<asp:GridView ID="grdSkill" runat="server" AutoGenerateColumns="False" Width="798px"
AllowPaging="True"
onpageindexchanging="grdSkill_PageIndexChanging"
onrowcommand="grdSkill_RowCommand"
onrowdeleting="grdSkill_RowDeleting"
onrowediting="grdSkill_RowEditing" Font-Bold="True"
Font-Names="Calibri" Font-Size="Medium" ForeColor="White" PageSize="5">
<Columns>
<asp:BoundField HeaderText="EmployeeSkillId" DataField="EmployeeSkillId" >
</asp:BoundField>
<asp:BoundField DataField="SkillName" HeaderText="Skill Name" ReadOnly="True">
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Skill Detail" DataField="SkillDetail"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" ImageUrl="images/updateIcon.png" CausesValidation="false" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeSkillId") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="images/deleteIcon.png" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeSkillId") %>' OnClientClick="return confirm('Are you sure you want to delete this record...');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#5D92B9" BorderStyle="None" />
<AlternatingRowStyle BackColor="#AAAAAA" />
</asp:GridView>
</ul>
</div>
<div>
<ul>
<li style="margin-top:20px; margin-left:20px; margin-bottom:15px"><input type="image" src="images/img_qualificationDetail.png" /></li>
</ul>
<ul>
<li>Course</li>
<li><asp:DropDownList runat="server" class="text_input" id="ddlCourse"/></li>
<li>Institution</li>
<li><asp:TextBox runat="server" class="text_input" id="txtInstitution"/></li>
<asp:RequiredFieldValidator ID="validatorInsitution" runat="server" ValidationGroup="course" ErrorMessage="*" ControlToValidate="txtInstitution"></asp:RequiredFieldValidator>
</ul>
<ul>
<li>Duration</li>
<li><asp:TextBox runat="server" class="text_input" id="txtCourseDuration"/></li>
<asp:RequiredFieldValidator ID="validatorDuration" runat="server" ValidationGroup="course" ErrorMessage="*" ControlToValidate="txtCourseDuration"></asp:RequiredFieldValidator>
<li>Passing Year</li>
<li>
<asp:TextBox ID="calPassingYear1" runat="server" CssClass="text_input"></asp:TextBox>
</li>
<!--<li><ew:CalendarPopup ID="calPassingYear" runat="server"></ew:CalendarPopup></li>-->
</ul>
<ul>
<li>Marks/Percentage/GPA</li>
<li><asp:TextBox runat="server" class="text_input" id="txtMarksPercentage"/></li>
<asp:RequiredFieldValidator ID="validatorMarks" runat="server" ValidationGroup="course" ErrorMessage="*" ControlToValidate="txtMarksPercentage"></asp:RequiredFieldValidator>
<li style="margin-left:160px">
<asp:ImageButton src="images/btn_Add.png" runat="server" ID="btnAddCourse" CausesValidation="True" onclick="btnAddCourse_Click" ValidationGroup="course"/>
<asp:ImageButton src="images/btnReset.png" runat="server" ID="btnResetCourse" CausesValidation="False" onclick="btnResetCourse_Click" />
</li>
</ul>
<ul style="margin-left:30px">
<asp:GridView ID="grdCourse" runat="server" AutoGenerateColumns="False" Width="798px"
AllowPaging="True"
onpageindexchanging="grdCourse_PageIndexChanging"
onrowcommand="grdCourse_RowCommand"
onrowdeleting="grdCourse_RowDeleting"
onrowediting="grdCourse_RowEditing" Font-Bold="True"
Font-Names="Calibri" Font-Size="Medium" ForeColor="White" PageSize="5">
<Columns>
<asp:BoundField DataField="EmployeeQualificationId"
HeaderText="EmployeeQualificationId" />
<asp:BoundField HeaderText="Course" DataField="CourseTitle" ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Institution" DataField="InstitutionName"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Duration" DataField="Duration"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Passing Year" DataField="YearOfPassing"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:BoundField HeaderText="Marks/Percentage/GPA" DataField="MarksPercentage"
ReadOnly="True" >
<ItemStyle Font-Names="Calibri,Verdana,Arial,Helvetica,sans-serif"
Font-Size="Small" ForeColor="#3F4A53" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgBtnEdit" runat="server" ImageUrl="images/updateIcon.png" CausesValidation="false" CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeQualificationId") %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgBtnDelete" runat="server" ImageUrl="images/deleteIcon.png" CommandName="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "EmployeeQualificationId") %>' OnClientClick="return confirm('Are you sure you want to delete this record...');"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#5D92B9" BorderStyle="None" />
<AlternatingRowStyle BackColor="#AAAAAA" />
</asp:GridView>
</ul>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<ul>
<li style="margin-left:90px; margin-bottom:10px;">
<asp:ImageButton ID="btnSubmit" AlternateText="submit button" runat="server" src="images/btn_Submit.png" onclick="btnSubmit_Click"/>
</li>
</ul>
</div>
<!--CLOSE CONTENT DIV-->
</asp:Content>
For Example:
When I was trying to add some ASP.NET server side controls like <asp:testBox id="txtBox" runat="server"/> they were not accessible in the code behind.:
Error: txtBox is not defined in the current Context ...
What am I doing wrong?
I had this problem when I moved a website into a main solution by creating an asp.net application project in the solution and copying aspx & aspx.cs files over. I solved it by right clicking on the project and converting to a web application. This created the necessary designer.cs files which contain the code for the asp objects on the aspx page.
This happens especially with older stuff in visual studio.
In 1.1 (before "partial classes") you could always see the control declarations in the code-behind.
In later versions, they moved that into a cs.designer file (so now you've got partial classes -- part in the .cs.designer file, and part in the .cs file).
If you're working with a visual studio "project", then you can open the cs.designer file, and add your control. Just look at how all of the other controls are declared -- that's all you have to do.
If you're working with a visual studio "website", then you're out of luck. There's no way to view or edit the cs.designer file, because it isn't there until the website is compiled.
Check to ensure the designer.cs file for the page is included in the project. Right click it and see if you get the option to "Include in project."
Just found this question, and I realise it's quite old, but I think I have a potential answer. Your code-behind for the designer's partial class might not be included in the project - sometimes happens when you've renamed and/or copied the file.
Go to your page (let's call it Test.aspx) and expand its tree in the Solution Explorer - do you see a file called Test.aspx.cs and Test.aspx.designer.cs? If not, look for a button at the top of the Solution Explorer marked Show All Files. Click it - if you now see the .designer.cs file there, right-click it and select "include in project". This got me going again after I ran into this problem.
if you are unable to find the control in .cs page, simply add the control reference in designer.cs page and try to access it again.
I'm sure it will 100%. this is what i learned
Have you renamed your project file? If you have, then remember to rename the Inherits at the top of your ASPX page.
Use CodeBehind attribute instead of CodeFile attribute of Page tag.
Eg:
<%# Control Language="C#" AutoEventWireup="true" **CodeBehind**="Results.ascx.cs" Inherits="MyApp.Results" %>
If you're experiencing this issue in VS2013 in a Website (as opposed to a Web Application) and have more than one aspx file sharing a codebehind then you need to make sure that ALL the aspx files have exactly the same collection of controls.
In previous versions of Visual Studio this wasn't an issue but it looks like VS2013 has tightened up.
I hope this helps someone - I only spotted it thanks to Sergey's comment above.
First
Make sure you assigned an ID to the
control
If this doesn't help
Close the page where you added the
control
Rebuild/compile the project
and open the page again
This happened to me in a website project in VS2010, but as I'm part of a larger team, I don't have the option to convert to Web Application as Domenic suggested.
It turns out it was because I had switched my default editor for ASPX files to "HTML Editor" instead of "Web Form Editor". I did this because intellisense was killing my computer whenever I opened an ASPX file. When I right clicked on this page to "Open With..." the "Web Form Editor", and added the controls again, it worked perfectly and they're now available in the code behind file.
Add an empty .aspx.designer.cs file to your project
To have visual studio autocreate declarations of .aspx page controls you can add an empty YourWebPageName.aspx.designer.cs -file to your project.
If added to the project externally you can add it to your project by right clicking the project, selecting new item and include the new .cs file into your project.
Then, as soon as you make a minor modification to your YourWebPageName page in the design editor Visual Studio will populate your empty .cs file with declarations.
Here are a list of troubleshooting I go through when I get similar problems.
Make sure the IDs you are tying to use in the code behind are actually declared in the markup
Make sure these elements have 'runat="server"'
If you are having problems with a specific control, try to create one near the top of the page, if that doesn't work either, it's a code generation problem
If 3. is your issue, temporarily remove the mark-up of the controls and any reference you had to them in the code behind, ie make it so you can successfully build. Close the designer.cs file if you have it open and do a rebuild. After which try to re-add a basic control (following step 1 and 2) and see if it shows up (it should). Then re-add your mark up as needed and you should find the code generation is working again.
manually enter declaration in other partial class
I had the same issue when 2 ASP Pages were using the same Code Behind file (It was ASP.NET Web Site project in Visual Studio 2013, not an ASP.NET Web Application). I have solved the problem by changing it to use different Code Behind files for each page.
Possible reasons:
id mismatch.
runat="server" not present in the control at .aspx file.
The solution that I found, apart from correcting the above, is to rebuild the project:
One more thing you need to take care is, before rebuild, close the designer file.
I had a similar problem. I faced this problem when I tried to rename the aspx file. In my case, the class name was not updated from UpdateRecords to ModifyRecords when I renamed the aspx file to ModifyRecords. Hence none of the ASP.NET controls were accessible from the code behind.
Code behind before renaming:
public partial class UpdateRecords : System.Web.UI.Page
Code behind after renaming:
public partial class ModifyRecords : System.Web.UI.Page
If you try to rename aspx file or copy-paste from different file, just make sure, the class name is updated.
Make sure the codeBehind attribute in page directive refer to the cs file where you call the control
I have the same problem. I found the solution by removing "PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>" from aspx page and it works normal now.
If your trying to access the tags from your own built in method on the back-end make sure that you don't make this method static - otherwise you wont have access to these tags...
<p #id="myTag" runat="server">...</p>
private static void myMethod(){
myTag.InnerText = "Hello" //You will not have access to this tag
}
private void myMethod(){
myTag.InnerText = "Hello"; //You have access to tags
}
Faced a similar problem because the controls were either within the:
"LoginView" or "AnonymousTemplate" and Viewstatemode was Disabled
Resolved by moving the Asp controls outside these tag elements
I also had a similar problem in the past. As you have mentioned that the project was previously built by someone else, So it must be coded in VB based coding and you can check that in web.config compilation details. Try copying the aspx page content onto your newly created C# aspx page and paste the code as well it will work.
Problem is you might have multiple aspx files with codefile in page directive points to same codebehind file.
It expects the same control to exists in all the aspx file linked to same code behind and thus throwing compilation error.
If you still having the issue cleaning up the same as mentioned above, check the designer page and regenerate one.
protected global::System.Web.UI.WebControls.CheckBox CheckBoxName ;
Add your control id name to your designer.cs and then it will be available in your cs file.
Very old question, but I ran into this issue today, and ended up figuring out a solution that I didn't see mentioned here. So, I'll share it.
There are three files in a page: the ASPX, the ASPX.CS, and the ASPX.Designer.CS
When you edit the HTML/Markup for the ASPX directly (like I prefer to do), it doesn't automatically update the designer. That's why it's not showing up in intellisense (at least for me). To get the IDE to update the designer, you have the ASPX page open in Visual Studio (and have it be the focused file); click on the "view" menu, and select "designer" (or hit Shift+F7); the IDE will show you the design view; right-click in the design area and select "refresh" from the context menu; save the file; select "markup" from the "view" menu (or hit Shift+F7 again); and check the designer file to see if the
controls you added now exist in the designer.
There might be a simpler way, but this worked for me to be able to access a control from the code behind that I had added to the HTML manually.
Make sure your control should have a generated code-behind reference at all! For example, if it’s in a list template then you’ll need to look up a reference to it in an item binding event handler.
This drove me wild because I had two controls with the same ID, one was at page level whereas the other was in a template.
I thought the generated reference I was using was for the one in the template and I couldn’t work out why a newly added control in the template wasn’t resulting in a generated reference.
I solved this problem by forcing the VS to regenerate my designer file. For that :
I deleted my designer.cs file.
Copied the designer file of another page.
Renamed the designer file and the partial class in it to match the name of my page code behind class.
Deleted everything from the designer class body.
Cut all the controls from the aspx markup page.
Saved the aspx page.
Pasted the controls back and saved the file again.
This made VS recreate all the controls in the blank designer file.
Hope that works for you.
This is an old one but I ran into the same issue today and after bumping my head here and there, I found out that controls you add in GridViews are generated dynamically so, you need to access them based on the index they are present at (Just like lists/arrays in regular programming) instead of IDs.
Hence, if you're adding your new controls in GridView, you will need to access them via indexes. A good practice would be to create ENUM in code behind for the GridView items indexes.
So old question,
But if it helps try to move controls outside any other control because accessing make different.

Really simple GridView ASP.NET question

Ok, this should be really easy, but I just don't have enough experience.
I need to throw a GridView on a WebForm and populate with a List, where Template is my class that has ID, Name, CreatedOn, etc... properties.
The GridView needs to display each Template Name as a link. The link should point to TemplateEdit.aspx page, with the following URL: TemplateEdit.aspx?ID={ID of Template}.
I also need a Delete link (preferably an image link), that should popup a Yes/No delete confirmation dialog.
I've actually done this before in 2005 or so, but I simply can't remember anymore.
Here's how you do it (borrowed the code from here to save some typing)
<asp:TemplateField HeaderText="Statement" SortExpression="Statement">
<ItemTemplate>
<asp:HyperLink ID="Link1" runat="server" NavigateUrl='<%# Bind("ID", "~/TemplateEdit.aspx?ID={0}") %>' Text="The Best Link"></asp:HyperLink >
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" Runat="server" ImageUrl="~/images/delete.gif" OnClientClick="return confirm('Are you sure you want to delete this?');" ToolTip="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
didn't actually test it, but looks like it should work.

Categories