Setting visibility of a link in code behind - c#

i have this in source code:
<a href="CreateAlbum.aspx" id="createalbumlink">
Create New Album
</a>
now i want to set its visibility in code behind. How can i do so? I have this link within ListView Control.
I replaced the above with
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/CreateAlbum.aspx"> Create New Album1</asp:LinkButton>
still couldnt detect in codebehind.
SOurce code:
<form id="form1" runat="server">
<asp:ListView ID="lvAlbums" runat="server"
DataSourceID="SqlDataSource1" GroupItemCount="3"
InsertItemPosition="LastItem">
<LayoutTemplate>
<table border="1">
<tr ID="groupPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<td ID="itemPlaceholder" runat="server">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td3" width="150px" height="150px" align="center" style="background-color: #e8e8e8;color: #333333;">
<asp:HiddenField ID="hfPhotoID" runat="server" Value='<%# Eval("DefaultPhotID") %>' />
<a href='<%# "Photos.aspx?AlbumID="+Eval("AlbumID") %>'>
<asp:Image CssClass="Timg" runat="server" ID="imPhoto" ImageUrl='<%# "ThumbNail.ashx?ImURL="+Eval("Photo") %>' />
</a>
<br />
<b><asp:Label ID="lblAlbumName" runat="server" Text='<%# Eval("AlbumName") %>'></asp:Label> </b>
</td>
</ItemTemplate>
<InsertItemTemplate>
<td id="Td3" width="150px" height="150px" runat="server" align="center" style="background-color: #e8e8e8;color: #333333;">
<asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/CreateAlbum.aspx"> Create New Album1</asp:LinkButton>
<%-- <a href="CreateAlbum.aspx" id="createalbumlink" runat="server">
Create New Album
</a>--%>
</td>
</InsertItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SLIITComDBConnectionString %>"
SelectCommand="SELECT Album.AlbumID, Album.DefaultPhotID, Album.AlbumName, PhotAlbum.Photo FROM Album INNER JOIN PhotAlbum ON Album.DefaultPhotID = PhotAlbum.PhotoID where album.userid=#userid">
<SelectParameters>
<asp:QueryStringParameter Name="userid" Type="int32" QueryStringField="id" />
<%--<asp:SessionParameter Name="userid" Type="String" SessionField="UserId" />--%>
</SelectParameters>
</asp:SqlDataSource>
</form>

Well you can't access the LinkButton directly since its inside a ListView, you can iterate through each item in the ListView and find the link button using FindControl and then set the Visible property. Something like:
foreach (ListViewItem item in listView.Items)
{
LinkButton linkButton = item.FindControl("LinkButton1") as LinkButton;
if (linkButton != null)
linkButton.Visible = false;
}
the above will disable LinkButton for all the items.

Use the OnClick event handler of the LinkButton and toggle the visibility there.

Somewhere in the code behind do this:
LinkButton1.Visible = false;

LinkButton1.Visible = false; //control will not rendered
LinkButton1.Attribute["styles"] = "display:none"; // control will be hidden
You can alse use tag, but you have to add runat="server" param

Edit
Try using FindControl:
LinkButton LinkButton1 = (LinkButton)ListView1.FindControl("LinkButton1");
LinkButton1.Visible = false;

Related

How to get Textbox from <ItemTemplate> in Repeater ASP Net

I have a product catalog page. When you click on the "Add Product" button, page with a cart shows up. This page has a table with an ItemTemplate inside it. Is there any way to get the value from the textBox located inside that ItemTemplate and change the value in the column Total cost in the table by clicking the button? The main problem is that I cannot access the textBox since it's in the . Thank you.
Catalog page:
Cart page:
CartView.aspx
MasterPageFile="~/Page/Store.Master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="bodyContent" runat="server">
<div id="content" style="margin-left: 7%;">
<style>
#import url("/css/tableCart.css");
#import url("/css/ButtonsCart.css");
</style>
<h2 style="padding: 14px; color:Highlight;">Ваша корзина</h2>
<h3 style="padding: 14px; color:Highlight;">Товары, которые вы добавили в корзину, представлены здесь</h3>
<table id="Table1" V class ="simple-little-table">
<thead>
<tr>
<th></th>
<th>Название</th>
<th>Цвет</th>
<th>Глубина</th>
<th>Ширина</th>
<th>Цена</th>
<th>Количество</th>
<th>Итого</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="Repeater1" ItemType="Line.Models.CartLine"
SelectMethod="GetCartLines" runat="server" EnableViewState="false">
<ItemTemplate>
<tr>
<td><asp:Image ID="Image1" runat="server" style="height:45px; " ImageUrl=<%# Item.Product.Img %> /></td>
<td> <%# Item.Product.NameProduct %> <%# Item.Product.TypeProducts %></td>
<td><%# Item.Product.Colors %></td>
<td>
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<asp:Button ID="cmdUpdate" OnClick="cmdUpdate_Click1" runat="server" Text="Update" CommandName="MyUpdate" CommandArgument = '<%# Container.ItemIndex %>'/>
</td>
<td><%# Item.Size.Depth%></td>
<td><%# Item.Product.Price%></td>
</td>
<td>
<td>
<asp:Label ID="Label2" runat="server" Text="<%# ((Item.Quantity *
Item.Product.Price))%>"></asp:Label>
</td>
<td>
<asp:Label ID="txtAmount" runat="server" Text=""></asp:Label>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
<tfoot>
<tr>
<td colspan="3">Итого:</td>
<td colspan="2" ><%= CartTotal.ToString("c") %></td>
</tr>
</tfoot>
</table>
</div>
</asp:Content>
CartView.aspx.cs
using Line.Helpers;
using Line.Models;
using Line.Models.Repository;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Line.Page
{
public partial class CartView : System.Web.UI.Page
{
protected void Page_Load(object sender, RepeaterCommandEventArgs e)
{
}
public IEnumerable<CartLine> GetCartLines()
{
return SessionHelper.GetCart(Session).Lines;
}
public decimal CartTotal
{
get
{
return SessionHelper.GetCart(Session).ComputeTotalValue();
}
}
public string CheckoutUrl
{
get
{
return RouteTable.Routes.GetVirtualPath(null, "checkout",
null).VirtualPath;
}
}
public string ReturnUrl
{
get
{
return SessionHelper.Get<string>(Session, SessionKey.RETURN_URL);
}
}
protected void cmdUpdate_Click1(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "MyUpdate")
{
RepeaterItem rRow = Repeater1.Items[Convert.ToInt32(e.CommandArgument)];
TextBox tQty = (TextBox)rRow.FindControl("txtQty");
Label tAmount = (Label)rRow.FindControl("txtAmount");
tAmount.Text = tQty.Text;
}
}
}
}
Ok, so you can set the index of the button, and pick this up in the Repeater "item command"
So, for your button, you can/want say this:
I have qty, price, and amount in the repeater. and button.
So, the markup can look like this:
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<br />
Price: <asp:TextBox ID="txtPrice" runat="server" Width="130px" />
<br />
Amount: <asp:TextBox ID="txtAmount" runat="server" Width="130px" />
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update"
CommandName="MyUpdate"
CommandArgument = '<%# Container.ItemIndex %>'/>
So, you are now free to enter Qty, amount in any of the repeated items.
I have this:
Now, my repeater is going accross - and I think you should be using a listview since that better supports a grid + columnar layout - but it really don't mater (listview, gridview, repeater - they all work the same).
So, note how in our button we have both command Name, and command argument. In command argument I pass the row of the repeater.
So, the code looks like this:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
// update button in repeater clicked
// update amount based on qty, and price
if (e.CommandName == "MyUpdate")
{
RepeaterItem rRow = Repeater1.Items(e.CommandArgument);
TextBox tQty = rRow.FindControl("txtQty");
TextBox tPrice = rRow.FindControl("txtPrice");
TextBox tAmount = rRow.FindControl("txtAmount");
tAmount.Text = tQty.Text * tPrice.Text;
}
}
So, just pass the "index" of the repeater row as per above. We used this expression as command argument:
<asp:Button ID="cmdUpdate" runat="server" Text="Update"
CommandName="MyUpdate"
CommandArgument = '<%# Container.ItemIndex %>'/>
So, once you have the Item Index (row index), then you can run code against the one row and change that row as per above.
Edit:
So the full markup I have is this:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="130px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
Qty: <asp:TextBox ID="txtQty" runat="server" Width="130px" />
<br />
Price: <asp:TextBox ID="txtPrice" runat="server" Width="130px" />
<br />
Amount: <asp:TextBox ID="txtAmount" runat="server" Width="130px" />
<br />
<asp:Button ID="cmdUpdate" runat="server" Text="Update" CommandName="MyUpdate" CommandArgument = '<%# Container.ItemIndex %>' />
<div>
City : <asp:DropDownList ID="cboCity" runat="server" DataTextField="City"
DataValueField="City" Width="110px">
</asp:DropDownList>
<div style="float:right;text-align:center;margin-left:4px;">
<asp:Button ID="cmdAddCity" runat="server" Text="+" OnClick="cmdAddCity_Click" Height="16px" Width="12px" Font-Size="XX-Small" cssclass="btnPad" OnClientClick="AddCity();return false"/>
</div>
</div>
Active: <asp:CheckBox ID="chkActive" runat="server" Checked = '<%# Eval("Active") %>'/>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
The code to load up this repeater is this:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
LoadGrid();
}
public void LoadGrid()
{
cmdSQL.Connection.Open();
strSQL = "SELECT ID, FirstName, LastName, HotelName, City, Active from tblHotels ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
rstTable.Load(cmdSQL.ExecuteReader);
Repeater1.DataSource = rstTable;
Repeater1.DataBind();
}
}
so the above fills out the repeater - as noted, for a grid like layout, I would use a listview. Drag a list view into a web page.
use the wizards to connect to the database. Now blow out all the templates, only leave the itemtemplate.
Your code to load up the grid - same as above.
now, in place of the repeater as per previous screen shots?
You get this:
So your multiple lines that your building? They should be based on and around a listview. And each row can thus be grabbed, and addressed just as I did per above.
Do a google for listview examples - there is a like a billion examples.
Once you have this setup, then each row is a "thing" that repeats for you automatic based on the data from the table.
The markup for the list view - it again quite much follows the same ideas and concepts as a repeator. the listview for above looks like this:
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID">
<ItemTemplate>
<tr style="">
<td><asp:Label ID="IDLabel" runat="server" Text='<%# Eval("ID") %>' /></td>
<td><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' /></td>
<td><asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' /></td>
<td><asp:Label ID="HotelNameLabel" runat="server" Text='<%# Eval("HotelName") %>' /></td>
<td><asp:Label ID="CityLabel" runat="server" Text='<%# Eval("City") %>' /></td>
<td><asp:CheckBox ID="ActiveCheckBox" runat="server" Checked='<%# Eval("Active") %>' Enabled="false" /></td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">ID</th>
<th runat="server">FirstName</th>
<th runat="server">LastName</th>
<th runat="server">HotelName</th>
<th runat="server">City</th>
<th runat="server">Active</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style=""></td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>

ASP.NET (C#) - ListView

In past, i worked on ListViews (.net 2.0) using a custom Template field but what i am trying to achieve here is the following
I am now working on .net 4.6
So basically a list which shows items like above and on mouse-hover few options show up as shown in the following screenshot
I also have to trigger those option to do different things -
How can I do that in asp.net, may I please have some code references.
Cheers
P.S.
This is a rough example of how i am creating the List Item Template (as requested)
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1">
<AlternatingItemTemplate>
<table >
<tr>
<td ><asp:Image ID="image1" ImageUrl='<%# Bind("url") %>' runat="server" Width="98px" /> </td>
<td><h2><asp:Label ID="_label" runat="server" Text ='<%# Bind("title") %>'></asp:Label></h2><asp:Label ID="Label1" runat="server" Text ='<%# Bind("description") %>'></asp:Label></td>
</tr>
</table>
</AlternatingItemTemplate>
<EmptyDataTemplate>
No data was returned.
</EmptyDataTemplate>
<ItemSeparatorTemplate>
<br />
</ItemSeparatorTemplate>
<ItemTemplate>
<table >
<tr>
<td ><asp:Image ID="image1" ImageUrl='<%# Bind("url") %>' runat="server" Width="98px" /> </td>
<td><h2><asp:Label ID="_label" runat="server" Text ='<%# Bind("title") %>'></asp:Label></h2><asp:Label ID="Label1" runat="server" Text ='<%# Bind("description") %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
<LayoutTemplate>
<ul id="itemPlaceholderContainer" runat="server" style="">
<li runat="server" id="itemPlaceholder" />
</ul>
<div style="">
</div>
</LayoutTemplate>
</asp:ListView>
I can add any html formatting to this template e,g i can add ASP:button etc but i don't know how to trigger those to perform certain tasks.
One easy way to achieve your requirement is to keep those buttons there but invisible and show them up when the parent container is hovered. following as a quick sample
aspx
<asp:ListView ID="ListView1" runat="server">
<ItemTemplate>
<tr class="row-data">
<td>
<asp:Label ID="NameLabel" runat="server" Text='<%# Eval("Name") %>' />
</td>
<td>
<asp:Label ID="PositionLabel" runat="server" Text='<%# Eval("Position") %>' />
</td>
<td>
<div class="btn-area">
<asp:Button runat="server" Text="Button1" />
<asp:Button runat="server" Text="Button2" />
</div>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table id="itemPlaceholderContainer" runat="server" border="0" style="">
<tr runat="server" style="">
<th runat="server">
Name
</th>
<th runat="server">
Position
</th>
<th>
</th>
</tr>
<tr id="itemPlaceholder" runat="server">
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
css
.btn-area
{
display: none;
}
.row-data:hover .btn-area
{
display: block;
}
code-behind
protected void Page_Load(object sender, EventArgs e)
{
ListView1.DataSource = new List<dynamic>() {
new { Name = "Andy", Position = "PG"},
new { Name = "Bill", Position = "SD"},
new { Name = "Caroline", Position = "Manager"}
};
ListView1.DataBind();
}
UPDATE
ListView ItemCommand can capture the postback by button pressed and CommandName makes you able to recognize which button fired it.
<asp:Button runat="server" Text="Button1" CommandName="c1" />
<asp:Button runat="server" Text="Button2" CommandName="c2" />
code-behind
protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "c1")
{
// do something when button1 pressed
}
else if (e.CommandName == "c1")
{
// do something when button2 pressed
}
}

The name 'control' does not exist in the current context

I am having trouble with an error on a site I am working on that I've inherited, upon grabbing the source from the repository and building, then clearing out a few reference errors, I am still getting over 1000 instances of this error:
The name 'pnlDetails' does not exist in the current context (replace 'panelDetails' with any of my control names).
what this would seem to indicate is that the controls referenced server side are not declared on the page, or don't have runat=server in them, but in fact they do. it could also be a problem of the inherits attribute not matching, but it does. I have searched stackoverflow and seen this question before, though after trying some of the solutions mentioned, they did not help. I do not have any designer files for my pages. Below are some snippets of code from the aspx and aspx.cs pages. (some information redacted to protect client privacy)
My question is, why can't i reference my controls on the server side? 'paneldetails', 'rpAddresses' etc.?
default.aspx:
<%# Page Title="" Language="C#" MasterPageFile="~/org.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="directory_Default" %>
<%# Register Assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=xxxx"
Namespace="System.Web.UI.WebControls" TagPrefix="asp" %>
<%# Register TagPrefix="nu" Namespace="Leap.NuCaptcha" Assembly="leapmarketing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" Runat="Server">
<title>xxxx</title>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphBreadCrumb" Runat="Server">
<div id="breadCrumbFrame">Home > xxx</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphBody" Runat="Server">
<h3 class="sectionTitle"> xxx </h3>
<!--//////////// Begin Searchbox Panel ////////////-->
<asp:Panel ID="pnlSearchbox" Visible="true" runat="server" DefaultButton="lnkSearch">
<div class="info">
xxx xxx.
</div>
<h3 style="padding-bottom: 10px;">xxx:</h3>
<p>xxx xxx.</p>
<br />
<br />
<div class="addressLine">
<asp:Label ID="lblFirstName" CssClass="addressLabel" runat="server" Text="First Name"></asp:Label>
<asp:TextBox ID="txtFirstName" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblLastName" CssClass="addressLabel" runat="server" Text="Last Name"></asp:Label>
<asp:TextBox ID="txtLastName" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblCity" CssClass="addressLabel" runat="server" Text="City"></asp:Label>
<asp:TextBox ID="txtCity" CssClass="addressEdit" runat="server"></asp:TextBox>
</div>
<div class="addressLine">
<asp:Label ID="lblDistrict" CssClass="addressLabel" runat="server" Text="District"></asp:Label>
<asp:DropDownList ID="ddlDistrict" CssClass="addressDropDown" runat="server" DataSourceID="dsDistricts"
DataTextField="Name" DataValueField="DistrictID"
AppendDataBoundItems="True">
<asp:ListItem Value="">All Districts</asp:ListItem>
</asp:DropDownList>
</div>
<div class="addressLine">
<asp:Label ID="lblSpecialty" CssClass="addressLabel" runat="server" Text="Specialty"></asp:Label>
<asp:DropDownList ID="ddlSpecialty" CssClass="addressDropDown" runat="server"
DataSourceID="dsSpecialties" DataTextField="xxx_certification"
DataValueField="QualificationID" AppendDataBoundItems="True">
<asp:ListItem Value="">All xxx</asp:ListItem>
</asp:DropDownList>
</div>
<div class="addressLine">
<div class="addressLabel"> </div>
<asp:LinkButton ID="lnkSearch" CssClass="navButton" runat="server"
onclick="lnkSearch_Click">Search</asp:LinkButton>
</div>
</asp:Panel>
<asp:LinqDataSource ID="dsDistricts" runat="server"
ContextTypeName="org.Xrm.XrmDataContext" Select="new (DistrictID, Name)"
TableName="Districts">
</asp:LinqDataSource>
<asp:LinqDataSource ID="dsSpecialties" runat="server"
ContextTypeName="org.Xrm.XrmDataContext"
Select="new (QualificationID, xxx_certification)" TableName="Qualifications"
Where="EducationTypeID == #EducationTypeID">
<whereparameters>
<asp:Parameter DefaultValue="000" Name="EducationTypeID"
DbType="Guid" />
</whereparameters>
</asp:LinqDataSource>
<!--//////////// Begin Search Results Panel ////////////-->
<asp:Panel ID="pnlResults" Visible="false" runat="server">
<div id="ResultsTop" style="margin-bottom: 15px;">
<div id="ResultsLeft" style="float: left; padding-top: 5px;">
<h2>Search Results - <span class="BlackResults">
<asp:Label ID="lblCount" runat="server" Text=""></asp:Label></span></h2>
</div>
</div>
<br />
<br />
<br />
<asp:LinkButton ID="lnkNewSearch" CssClass="navButtonLarge" runat="server" OnClick="lnkNewSearch_Click">New Search</asp:LinkButton>
<br />
<br />
<div align="center">
<asp:DataPager ID="DataPager2" runat="server" PagedControlID="lvResults"
PageSize="25">
<fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="True" />
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField ShowLastPageButton="True"
ShowNextPageButton="True" ShowPreviousPageButton="False" />
</fields>
</asp:DataPager>
</div>
<br />
<asp:ListView ID="lvResults" runat="server" DataSourceID="dsSearchResults">
<itemtemplate>
<tr style="">
<td class="DirectoryItems">
<asp:LinkButton ID="lnkDetails" CommandArgument='<%# Eval("ID") %>' OnCommand="lnkDetails_Click" runat="server"><%# Eval("xxx") %></asp:LinkButton>
</td>
<td class="DirectoryItems">
<asp:Label ID="LocationLabel" runat="server" Text='<%# Eval("Location") %>' />
</td>
<td class="DirectoryItems">
<asp:Label ID="StatusLabel" runat="server" Text='<%# Eval("Status") %>' />
</td>
</tr>
</itemtemplate>
<emptydatatemplate>
<table runat="server" style="">
<tr>
<td>
No data was returned.</td>
</tr>
</table>
</emptydatatemplate>
<layouttemplate>
<table runat="server" width="100%">
<tr runat="server">
<td runat="server">
<table ID="itemPlaceholderContainer" runat="server" border="0" style="border-collapse: collapse;" width="99%">
<tr runat="server" style="border-bottom:1px solid #828283; margin-top:5px; margin-bottom:5px; padding-top:5px; padding-bottom:5px;">
<td runat="server" width="40%">
<p class="DirectoryResultsHeader">xxx</p></td>
<td runat="server" width="30%">
<p class="DirectoryResultsHeader">Location</p></td>
<td runat="server" width="30%">
<p class="DirectoryResultsHeader">Status</p></td>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
</table>
</td>
</tr>
<tr runat="server">
<td runat="server" style="">
</td>
</tr>
</table>
</layouttemplate>
</asp:ListView>
<br />
<br />
<div align="center">
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvResults"
PageSize="25">
<fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="True" />
<asp:NumericPagerField ButtonCount="10" />
<asp:NextPreviousPagerField ShowLastPageButton="True"
ShowNextPageButton="True" ShowPreviousPageButton="False" />
</fields>
</asp:DataPager>
</div>
<asp:SqlDataSource ID="dsSearchResults" runat="server" OnSelected="dsSearchResults_Selected"
ConnectionString="<%$ ConnectionStrings:MSCRM %>" CancelSelectOnNullParameter="false"
SelectCommand="
SELECT * from sometable
">
<selectparameters>
<asp:ControlParameter ControlID="txtFirstName" DbType="String" Name="FirstName" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="txtLastName" DbType="String" Name="LastName" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="txtCity" DbType="String" Name="City" DefaultValue="" ConvertEmptyStringToNull="false" />
<asp:ControlParameter ControlID="ddlDistrict" DbType="Guid" Name="District" ConvertEmptyStringToNull="true" />
<asp:ControlParameter ControlID="ddlSpecialty" DbType="Guid" Name="Specialty" ConvertEmptyStringToNull="true" />
</selectparameters>
</asp:SqlDataSource>
</asp:Panel>
<!--//////////// Begin Details Panel ////////////-->
<asp:Panel ID="pnlDetails" Visible="false" runat="server">
<h3>xxx Information</h3>
<br />
<asp:Repeater ID="rpDetails" runat="server" DataSourceID="dsDetails">
<itemtemplate>
<table border="0">
<tr>
<td width="125"><b>Given Name:</b></td>
<td><%# Eval("FirstName") %></td>
</tr>
<tr>
<td width="125"><b>Surname:</b></td>
<td><%# Eval("LastName") %></td>
</tr>
<tr>
<td width="125"><b>Gender:</b></td>
<td><%#Eval("Gender") %></td>
</tr>
<tr>
<td width="125"><b>Status:</b></td>
<td><%# Eval("Status") %></td>
</tr>
<asp:Panel ID="pnlSpecialty" runat="server" Visible='<%# Eval("Status").ToString() == "xxx" || Eval("Status").ToString() == "xxx" || Eval("Status").ToString() == "xxx" ? true : false %>'>
<tr>
<td width="125"><b>xxx:</b></td>
<td>
<asp:Repeater ID="xxx" runat="server" DataSourceID="xxx">
<ItemTemplate>
<%# Eval("xxx") %><br />
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</asp:Panel>
<tr>
<td width="125"><b>xxx:</b></td>
<td><%# Eval("xxx") %></td>
</tr>
</table>
</itemtemplate>
</asp:Repeater>
<br />
<br />
<asp:Repeater ID="rpAddresses" runat="server" DataSourceID="dsAddresses" OnItemDataBound="rpAddresses_DataBound">
<headertemplate>
<h3>xxx</h3><br />
</headertemplate>
<itemtemplate>
<table border="0">
<tr>
<td valign="top" width="125"><b><asp:Label ID="lblAddressType" runat="server" Text='<%# Eval("Type") %>' /></b></td>
<td valign="top">
<asp:Label ID="lblAddressStreet1" runat="server" Text='<%# Eval("Street1") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street1")) ? false : true %>' />
<asp:Label ID="lblAddressStreet2" runat="server" Text='<%# Eval("Street2") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street2")) ? false : true %>' />
<asp:Label ID="lblAddressStreet3" runat="server" Text='<%# Eval("Street3") + "<br />" %>' Visible='<%# Convert.IsDBNull(Eval("Street3")) ? false : true %>' />
<asp:Label ID="lblAddressCity" runat="server" Text='<%# Eval("City") %>' />, <asp:Label ID="lblAddressProvince" runat="server" Text='<%# Eval("Province") %>' /> <asp:Label ID="lblAddressPostalCode" runat="server" Text='<%# Eval("PostalCode") %>' /><br />
<asp:Label ID="lblAddressCountry" runat="server" Text='<%# Eval("Country") + "<br />" %>' Visible='<%# (Eval("Country", "{0}") == "Canada") ? false : true %>' />
<table border="0">
<asp:Label ID="lblAddressPhone" runat="server" Text='<%# "<tr><td width=50>Phone:</td><td>" + Eval("Phone") + "</td></tr>" %>' Visible='<%#Convert.IsDBNull(Eval("Phone")) ? false : true %>' />
<asp:Label ID="lblAddressFax" runat="server" Text='<%# "<tr><td width=50>Fax:</td><td>" + Eval("Fax") + "</td></tr>" %>' Visible='<%#Convert.IsDBNull(Eval("Fax")) ? false : true %>' />
<asp:PlaceHolder ID="cphEmailAddress" runat="server" Visible='<%# Convert.IsDBNull(Eval("Email")) ? false : true %>'><tr><td width="50">Email:</td><td><asp:LinkButton ID="lnkEmailValidate" runat="server" Text='<%# Eval("ShortEmail") %>' OnClick="ShowReCAPTCHA" /></td></tr></asp:PlaceHolder>
<asp:PlaceHolder ID="cphEmail" runat="server" Visible="false"><tr><td width="50">Email:</td><td><asp:HyperLink ID="lnkEmail" runat="server" NavigateUrl='<%# Eval("Email", "mailto:{0}") %>' Text='<%# Eval("Email") %>' /></td></tr></asp:PlaceHolder>
</table>
<asp:PlaceHolder ID="cphCaptcha" runat="server" Visible="false">
<br />
<div class="info">To view the full email address, please type the moving characters in the box below.</div>
<nu:NuCaptchaControl ID="nucaptcha" runat="server" ClientKey="LEAP|0|4|TYPE|9|CLIENTKEY|CID|4|9942|KID|4|9884|SKEY|32|bDdiOWgwdjhtNy1MdTRENG43Q1BZdyws" />
</asp:PlaceHolder>
</td>
</tr>
</table>
<br />
</itemtemplate>
</asp:Repeater>
<br />
<br />
<asp:LinkButton ID="lnkDetailsBack" CssClass="navButtonLarge" runat="server" OnClick="lnkDetailsBack_Click">Back to Search Results</asp:LinkButton>
<asp:LinkButton ID="lnkDetailsNewSearch" runat="server" CssClass="navButtonLarge" OnClick="lnkNewSearch_Click">New Search</asp:LinkButton>
<asp:SqlDataSource ID="dsDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:MSCRM %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsSpecialty" runat="server"
ConnectionString="<%$ ConnectionStrings:MSCRM %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsAddresses" runat="server"
ConnectionString="<%$ ConnectionStrings:xxx %>"
SelectCommand="
SELECT * from some table
">
<selectparameters>
<asp:Parameter DbType="Guid" Name="ContactID" />
</selectparameters>
</asp:SqlDataSource>
</asp:Panel>
<!--//////////// Begin Data Sources ////////////-->
</asp:Content>
default.aspx.cs
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class directory_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack && pnlDetails.Visible == true && rpAddresses.Items.Count > 0 && ((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible == true)
{
Page.Validate();
if (Page.IsValid)
{
((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible = false;
((PlaceHolder)rpAddresses.Items[0].FindControl("cphEmailAddress")).Visible = false;
((PlaceHolder)rpAddresses.Items[0].FindControl("cphEmail")).Visible = true;
}
}
}
protected void rpAddresses_DataBound(object sender, EventArgs e)
{
}
protected void lnkSearch_Click(object sender, EventArgs e)
{
//lvResults.DataBind();
DataPager1.SetPageProperties(0, DataPager1.PageSize, true);
ShowResults();
}
protected void ShowResults()
{
pnlSearchbox.Visible = false;
pnlResults.Visible = true;
pnlDetails.Visible = false;
}
protected void lnkNewSearch_Click(object sender, EventArgs e)
{
pnlSearchbox.Visible = true;
pnlResults.Visible = false;
pnlDetails.Visible = false;
}
protected void lnkDetails_Click(object sender, CommandEventArgs e)
{
dsDetails.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
dsSpecialty.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
dsAddresses.SelectParameters["ContactID"].DefaultValue = e.CommandArgument.ToString();
rpAddresses.DataBind();
if (rpAddresses.Items.Count == 0)
{
rpAddresses.Visible = false;
}
else
{
rpAddresses.Visible = true;
}
pnlSearchbox.Visible = false;
pnlResults.Visible = false;
pnlDetails.Visible = true;
}
protected void lnkDetailsBack_Click(object sender, EventArgs e)
{
ShowResults();
}
protected void dsSearchResults_Selected(object sender, SqlDataSourceStatusEventArgs e)
{
lblCount.Text = String.Format("{0} Dentists found", e.AffectedRows);
}
protected void ShowReCAPTCHA(object sender, EventArgs e)
{
((PlaceHolder)rpAddresses.Items[0].FindControl("cphCaptcha")).Visible = true;
}
}
Thanks for the answers people, I did try some of these things.
Every control which you wish to access in aspx.cs should have runat="server"
they do
Build your solution after adding the above tag
If you wish to access the control defined inside the item template of repeater you
can do so only inside repeater events for by putting a loop reading
all items of repeater
they are
Right click on the page where you are getting the error and click on
convert to web application... That will solve your error.
no such option in my IDE, besides I think it would be the whole project, not a page that I convert.
Check to see if this is a web application project or a website
project. A website project would use the CodeFile attribute of the
#Page directive, but a web application project wouldn't. If it's
trying to compile as a web application project, you would receive
these errors because a web application project expects a designer file
in addition to the .aspx and .aspx.cs files. The designer contains all
the control definitions which in turn which allows you to reference
them properly in codebehind (web application uses CodeBehind and not
CodeFile attribute as well).
apparently then my project is a website, not a web application, as it includes the codefile attribute. also, I don't have designer files, so this makes sense.
Turns out I am trying to edit a solution developed in VS2008, using VS2013, and a lot has changed since then. While the issue was not resolved here, the fix was to create a new VS2013 solution and import the files, it's all working as intended now, thank you.
exclude or delete any other pages that reference the same code-behind file, for example an older page that you copied and pasted.
You may want to check the build action of the c# files in the property window in visual studio and make sure its set to Compile
Check to see if this is a web application project or a website project. A website project would use the CodeFile attribute of the #Page directive, but a web application project wouldn't. If it's trying to compile as a web application project, you would receive these errors because a web application project expects a designer file in addition to the .aspx and .aspx.cs files. The designer contains all the control definitions which in turn which allows you to reference them properly in codebehind (web application uses CodeBehind and not CodeFile attribute as well).
Right click on the page where you are getting the error and click on convert to web application... That will solve your error.
Couple of things to be checked here:
1. Every control which you wish to access in aspx.cs should have runat="server"
2. Build your solution after adding the above tag
3. If you wish to access the control defined inside the item template of repeater you can do so only inside repeater events for by putting a loop reading all items of repeater
I had this error but had just made a silly mistake. I wanted to retain the original code while I made some big changes so I copied and pasted one of the .cs files. Well, both files had the same class name. The two identical namespaces (understandably) confused the compiler. Removing the "backup" fixed it. I could have just changed the namespace, too.
Just sharing in case someone is as bone-headed as I.

Find Controls nested inside Repeater Control

I'm trying to find the values of TextBoxes which are rendered in a Repeater though a UserControl, i.e. the Repeater has a Placeholder for the UserControl, and inside the UserControl is where the TextBox markup actually exists. I've done this before with TextBoxes directly inside of a Repeater before, which was fairly straight forward, and I'm wondering why this apparently can't be accomplished the same way. Here is the Default page with the Repeater, which contains a Placeholder...
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<form class="formee">
<fieldset>
<legend>Faculty Information</legend>
<div class="grid-4-12">
<asp:Label ID="lblFirstName1" runat="server" Text="First Name"></asp:Label>
<asp:Label ID="lblFirstName2" runat="server" Text="" ></asp:Label>
<asp:Label ID ="lblSalary" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</div>
<div class="grid-6-12">
<asp:Label ID="lblLastName1" runat="server" Text="Last Name"></asp:Label>
<asp:Label ID="lblLastName2" runat="server" Text=""></asp:Label>
</div>
</fieldset>
</form>
<div id="repeaterDiv">
<asp:Repeater ID="rptBudget" runat="server" ClientIDMode="Static">
<ItemTemplate>
<asp:PlaceHolder ID="phBudget" runat="server" EnableViewState="true" />
<br />
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnAddBudgetControl" runat="server" Text="Add"
CausesValidation="false" OnClick="AddBudgetControl" CssClass="addBudgetControl"/>
<asp:Button ID="btnDisplayEntries" runat="server" Text="Display Entries" CausesValidation="false" OnClick="DisplayEntries" />
</div>
<div>
<asp:TextBox ID="txtTotalPercent" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:TextBox ID="txtGrandTotal" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Label ID="lblCtrls" runat="server" Text=""></asp:Label>
</div>
...and the UserControl which is inserted in the place of the Placeholder...
<fieldset>
<legend>Faculty Salary Form</legend>
<table cellspacing="10" id="values">
<tr>
<td>
<asp:Label ID="lblServiceType" runat="server" Text="Service"></asp:Label>
<asp:DropDownList runat="server" ID="ddlServiceType" CssClass="serviceType" />
</td>
<td>
<asp:Label ID="lblSpeedCode" runat="server" Text="Speed Code"></asp:Label>
<asp:DropDownList runat="server" ID="ddlSpeedCode" CssClass="speedType" />
</td>
<td>
<asp:Label ID="lblPercentage" runat="server" Text="Percentage"></asp:Label>
<asp:Textbox ID="txtPercentage" runat="server" CssClass="percentCommitment" ClientIDMode="Static" EnableViewState="true" />
</td>
<td>
<asp:Label ID="lblTotal" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="txtTotal" runat="server" CssClass="amountCommitment" ClientIDMode="Static" EnableViewState="true"/>
</td>
<td>
<asp:Button ID="btnRemove" runat="server" Text="Remove Item" OnClick="RemoveItem" ClientIDMode="Static" CssClass="btnRemove" />
</td>
</tr>
<tr>
</tr>
</table>
</fieldset>
...but when the following code runs for the Display button's OnClick, I always get a null value for any and all TextBoxes (and DropDowns) in the UserControl...
protected void DisplayEntries(object sender, EventArgs e)
{
foreach (RepeaterItem repeated in rptBudget.Items)
{
TextBox txtPercentage = (TextBox)repeated.FindControl("txtPercentage");
if (txtPercentage == null)
{
lblCtrls.Text += " null; ";
}
else
{
lblCtrls.Text += txtPercentage.Text + "; ";
}
}
}
What's the best way to access these values? Thanks.
txtPercentage Textbox is located inside Usercontrol, so use the following helper method to retrieve it.
Helper Method
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Usage
foreach (RepeaterItem repeated in rptBudget.Items)
{
TextBox txtPercentage =
(TextBox)FindControlRecursive(repeated, "txtPercentage");
...
}
Try loading the placeholder first and then looking for the textboxes in the placeholder:
Something like this:
pseudo
var ph = repeated.FindControl("phBudget");
var txtBox = ph.FindControl("txtPercentage");
/pseudo
You need to first get the UserControl, then use FindControl on the UC itself.

div tag visible attribute is not working

I use web control in asp.net using c#. I use div tag. on btnProviderSubmit1 i change visibility of divprov. but divprov is not visible false. It visible.
pos.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="pos.ascx.cs" Inherits="USerControls_Recharge_pos" %>
<%# Register Assembly="Gaia.WebWidgets" Namespace="Gaia.WebWidgets" TagPrefix="gaia" %>
<form id="Form1" runat="server">
<div>
<div>
<asp:LinkButton runat="server" ID="moveTo" Text="Go To Classical Mode" PostBackUrl="~/DesktopModules/Recharge/Recharge.aspx" OnClick="SaveCookies"/>
</div>
<div title="Select Provider" id="divprov" **visible="true"** runat="server" style="border-width:medium;border-color:Blue;border-width:medium;">
<asp:ListView DataSourceID="ObjectDataSource1" GroupItemCount="12" GroupPlaceholderID="groupPlaceholder" ItemPlaceholderID="itemPlaceholder" ID="ddlprovider" runat="server">
<LayoutTemplate >
<table runat="server" id="table2" style="border-width:medium" cellpadding="3">
<tr runat="server" id="groupPlaceholder">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr runat="server" id="productRow" style="height:80px">
<td runat="server" id="itemPlaceholder">
</td>
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td2" valign="top" align="center" style="width:100" runat="server">
<gaia:ImageButton runat="server" CommandArgument='<%#Eval("providerID") %>' **OnCommand="btnProviderSubmit1"** ImageUrl='<%# getImageURL(Eval("providerCode")) %>' ID="ImageButton1" /><br />
<gaia:LinkButton runat="server" CommandArgument='<%#Eval("providerID") %>' OnCommand="btnProviderSubmit1" Text='<%#Eval("description") %>' ID="lnkButton1"/>
</td>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DeleteMethod="Delete" InsertMethod="Insert"
OldValuesParameterFormatString="original_{0}" SelectMethod="FetchAll"
TypeName="mogile.MidTier.DAL.ProviderController" UpdateMethod="Update">
</asp:ObjectDataSource>
</div>
<div>
<gaia:Panel runat="server" ID="pnlCircle" Visible="false" ScrollBars="Auto">
<asp:ListView ID="ddlCircle" GroupItemCount="8" GroupPlaceholderID="groupPlaceholder" ItemPlaceholderID="itemPlaceholder" runat="server" DataSourceID="ObjectDataSource2">
<LayoutTemplate>
<table runat="server" id="table2" cellpadding="3">
<tr runat="server" id="groupPlaceholder">
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr runat="server" id="tableRow">
<td runat="server" id="itemPlaceholder" />
</tr>
</GroupTemplate>
<ItemTemplate>
<td id="Td1" runat="server">
<gaia:LinkButton ID="LinkButton1" OnCommand="btnCircleSubmit" Font-Size="Larger" BorderColor="red" BorderWidth="4px" runat="server" CommandArgument='<%#Eval("StateID") %>' Text='<%#Eval("StateName") %>'/>
</td>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
DeleteMethod="Delete" InsertMethod="Insert"
OldValuesParameterFormatString="original_{0}" SelectMethod="FetchAll"
TypeName="mogile.MidTier.DAL.StateController" UpdateMethod="Update">
</asp:ObjectDataSource>
</gaia:Panel>
</div>
</div></form>
pos.ascx.cs
public partial class USerControls_Recharge_pos : System.Web.UI.UserControl
{
private static int itemid = 0;
private static string circleCode;
private static string pdfText;
private static string providerName;
private static string productGrp;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnProviderSubmit1(object sender, CommandEventArgs e)
{
providerName = e.CommandArgument.ToString();
loadProductGroups(e.CommandArgument.ToString());
pnlCircle.Visible = true;
**divprov.Visible = false;**
}
protected void btnCircleSubmit(object sender, CommandEventArgs e)
{
circleCode = e.CommandArgument.ToString();
pnlProductGrp.Visible = true;
// pnlCircle.ForceAnUpdate();
}
}
A workaround could probably be to add "display:none" (or was it "visibility:hidden"? - you can google here) to the style attribute programatically in the btnClick handler.

Categories

Resources