I have create a photo gallery user control that show photographer in a fancy box.
I also use this control on several page to show page related photos. In hide photogallery user control if their are no photos for perticular page. For this i pass public event
public event SendMessageToThePageHandler showGallery;
to pass a boolean value to hide and show usercontrol on the page.
Page runs without any errors and show the gallery. But problem is with the Pager which doesn't work the way i am coded it. It generate NullReferenceException when i click on the page 2 or the gallery
I would appreeciate a more professional approach to this scenario in which i can pass passvalue to parent page correctly to hide/show correctly.
I am also using UpdatePanel in my usercontrol. Below is the sample code from Parent Page & User Control page
PageOne.aspx
<uc1:PhotoGallery ID="ucPhotoGallery" runat="server" />
CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
int _LangID = int.Parse(Helper.GetAppSettingValue("EnglishLanguageID"));
if (string.IsNullOrEmpty(Request["PID"]))
{
_LID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["LID"].ToString());
_PID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
getPageDetails(_PID);
getPageSubMenus(_PID);
// WriteThisMessageToThePage1.sendMessageToThePage += delegate(string message)
ucPhotoGallery.showGallery += delegate(bool showControl)
{
bool bShowControl = showControl;
ucPhotoGallery.Visible = bShowControl;
};
}
else
{
Response.Write("Page not be found, Wrong URL");
}
}
catch (Exception ex)
{
}
}
}
Photo-Gallery.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="Photo-Gallery.ascx.cs" Inherits="Photo_Gallery" %>
<%# Register Src="~/en/UserControls/PagerControl.ascx" TagName="PagerControl" TagPrefix="uc1" %>
<div class="uc-gallery-wrapper">
<div class="page-title-side-wrapper"><h5><asp:Label ID="lblPageTitleSide" CssClass="lbl-page-title-side" runat="server" Text=" Gallery"></asp:Label></h5></div>
<asp:UpdatePanel ID="updPnlAlbums" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="rptAlbums-wrapper">
<asp:Repeater ID="rptAlbums" runat="server" >
<ItemTemplate>
<div class="uc-album-wrapper">
<div class="uc-album-icon"><asp:Image ID="imgAlbumIcon" CssClass="uc-album-img" ImageUrl='<%# getImage(Eval("AlbumIcon")) %>' AlternateText='<%# getTitle(Eval("AlbumName")) %>' runat="server" /></div>
<div class="uc-album-name">
<asp:HyperLink ID="hylnkAlbum" CssClass="fancybox-iframe" runat="server" NavigateUrl='<%# getAID(Eval("AlbumID")) %>'>
<asp:Label ID="lblAlbumName" runat="server" Text='<%# getTitle(Eval("AlbumName")) %>'></asp:Label>
</asp:HyperLink>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
<div class="uc-gallery-pager-wrapper-o">
<div class="uc-pager-wrapper-i">
<uc1:PagerControl ID="PagerControl1" runat="server" CssClass="gold-pager" PageMode="LinkButton" />
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="updPnlAlbums" Visible="False">
<ProgressTemplate>
<div id="imgLoadingNewsList" class="uc-PagerLoading">
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/Images/preloader-160x15.gif" Visible="false" AlternateText="loading" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
<!-- UpdatePanel -->
</div>
CODE BEHIND
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using System.Data;
using CMS.SqlHelper;
using CMS.DataAccessLayer;
using System.Text;
public delegate void SendMessageToThePageHandler(bool showGallery);
public partial class Photo_Gallery : System.Web.UI.UserControl
{
int _PageID = 0;
public event SendMessageToThePageHandler showGallery;
protected void Page_Load(object sender, EventArgs e)
{
PagerControl1.PagerControl_PageIndexChanged += new EventHandler(PagerControl1_PagerControl_PageIndexChanged);
Page.MaintainScrollPositionOnPostBack = false;
if (!IsPostBack)
{
if (string.IsNullOrEmpty(Request["PID"]))
{
_PageID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
//_PageID = 3;
getAlbumByPageID(3);
}
else
{
Response.Write("Page not be found, Wrong URL");
}
}
}
public void getAlbumByPageID(int _PageID)
{
PagerControl1.PageSize = 2;
PagerControl1.DisplayEntriesCount = 5;
//Will show 2 links after ...
PagerControl1.EdgeEntriesCount = 0;
DataSet ds = DataProvider.GetAlbumByPageID(_PageID);
DataView dv = ds.Tables[0].DefaultView;
if (ds.Tables[0].Rows.Count > 0)
{
showGallery(true);
}
else
{
showGallery(false);
}
//pass the datatable and control to bind
PagerControl1.BindDataWithPaging(rptAlbums, dv.Table);
}
void PagerControl1_PagerControl_PageIndexChanged(object sender, EventArgs e)
{
_PageID = int.Parse(HttpContext.Current.Request.RequestContext.RouteData.Values["PID"].ToString());
getAlbumByPageID(_PageID);
}
}
WORK AROUND
I found a work around by wrapping my users control in a panel and hide/show panel if i have photos for that page or not. This is working fine but i still want to fix problem i have or even a better way of doing it.
<asp:Panel ID="pnl_uc_Gallery" runat="server" Visible="false">
// I have PUT all the USER CONTROL CODE In SIDE THIS BLOAK
</asp:Panel>
if (ds.Tables[0].Rows.Count > 0)
{
// showGallery(true);
pnl_uc_Gallery.Visible = true;
}
else
{
//showGallery(false);
pnl_uc_Gallery.Visible = false;
}
This code:
ucPhotoGallery.showGallery += delegate(bool showControl)
{
bool bShowControl = showControl;
ucPhotoGallery.Visible = bShowControl;
};
is in a !Page.IsPostback call; move it outside so that you are attaching to the event on every postback, not just the first one, or use a method as the event handler and set the method name in the markup. Either way, the issue is the event handler is established only on the first page load, not subsequent loads, and it needs to be done every time a request hits the server.
Related
Please consider this scenario:
I have a simple page and I want to log all controls causing postback. I create this simple page. It contains a grid to show some URLs and when user click on an icon a new tab should open:
<form id="form1" runat="server">
<div>
<table style="width: 100%;">
<tr>
<td style="background-color: #b7ffbb; text-align: center;" colspan="2">
<asp:Button ID="Button3" runat="server" Text="Click Me First" Height="55px" OnClick="Button3_Click" />
</td>
</tr>
<tr>
<td style="background-color: #f1d8fe; text-align: center;" colspan="2">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" BackColor="White" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField DataField="SiteAddress" HeaderText="Address" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" ImageUrl="~/download.png" runat="server" CommandArgument='<%# Eval("SiteAddress") %>' CommandName="GoTo" Height="32px" Width="32px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</div>
</form>
and code behind:
public partial class WebForm2 : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button3_Click(object sender, EventArgs e)
{
List<Address> Addresses = new List<Address>()
{
new Address(){ SiteAddress = "https://google.com" },
new Address(){ SiteAddress = "https://yahoo.com" },
new Address(){ SiteAddress = "https://stackoverflow.com" },
new Address(){ SiteAddress = "https://learn.microsoft.com/}" }
};
GridView1.DataSource = Addresses;
GridView1.DataBind();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "MyScript", "window.open('" + e.CommandArgument.ToString() + "', '_blank')", true);
}
}
class Address
{
public string SiteAddress { get; set; }
}
every thing is fine till here. Now I create a base class for all of my pages and add below codes for finding postback control:
public class MyPageBaseClass : Page
{
protected override void OnInit(EventArgs e)
{
if (!IsPostBack)
{
}
else
{
var ControlId = GetPostBackControlName(); <------
//Log ControlId
}
base.OnInit(e);
}
private string GetPostBackControlName()
{
Control control = null;
string ctrlname = Page.Request.Params["__EVENTTARGET"];
if (ctrlname != null && ctrlname != String.Empty)
{
control = Page.FindControl(ctrlname);
}
else
{
foreach (string ctl in Page.Request.Form)
{
Control c;
if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
{
string ctrlStr = ctl.Substring(0, ctl.Length - 2);
c = Page.FindControl(ctrlStr);
}
else
{
c = Page.FindControl(ctl);
}
if (c is System.Web.UI.WebControls.Button ||
c is System.Web.UI.WebControls.ImageButton)
{
control = c;
break;
}
}
}
if (control != null)
return control.ID;
else
return string.Empty;
}
}
and change this line:
public partial class WebForm2 : MyPageBaseClass
Now when I click on icons grid view disappears...(STRANGE...) and nothing happened. When I comment specified line then every thing will be fine...(STRANGE...).
In GetPostBackControlName nothings changed to Request but I don't know why this happened. I checked and I see if I haven't RegisterStartupScript in click event every thing is fine. Please help we to solve this problem.
Thanks
when I click on icons grid view disappears...
ASP.Net page class object instances only live long enough to serve one HTTP request, and each HTTP request rebuilds the entire page by default.
Every time you do a postback, you have a new HTTP request and therefore a new page class object instance and a completely new HTML DOM in the browser. Any work you've done for a previous instance of the page class — such as bind a list of addresses to a grid — no longer exists.
You could fix this by also rebuilding your grid code on each postback, but what I'd really do is skip the whole "RegisterStartupScript" mess and instead make the grid links open the window directly, without a postback at all.
The problem is related to OnInit event. I replaced it with OnPreLoad and every things is fine now.
For search engines: OnInit event has conflict with RegisterStartupScript
I am trying to make the input box show some text in the asp.net using c#, but after I run the code behind, nothing is displayed in the input box. The ui is RadNumericTextBox uiDistance. In class, I put this.uiDistance.Text = "123"; But in the webpage after run the code. I cannot see "123" is put in the uiDistance text box. How can I fix it?
Here is my aspx UsageControl2SubControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UsageControl2SubControl1.ascx.cs" Inherits="WebControls.UsageControl2SubControl1" %>
<asp:HiddenField ID="uiRemoved" Value="false" runat="server" />
<asp:HiddenField ID="uiID" runat="server" />
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
<div class="hr-line-dashed"></div>
And Here is my code behind: UsageControl2SubControl1.ascx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
namespace WebControls
{
public partial class UsageControl2SubControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
}
protected void uiAdd_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void uiRemove_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void RadComboBoxProduct_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
}
protected void uiAdd_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiRemove_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Text = "123";
}
}// end class
}// end namespace
Just to update your aspx code little bit
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
As your textbox is only inside the update panel so, on post back only that portion is partially updated, you need to put RadNumericTextBox inside the update panel too.
Hope this will work.
You are using the wrong property. Use Value not Text
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Value = "123";
}
As always, check the documentation. See: https://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/features/getting-and-setting-values
Your current code will works only when you tab out from uiToLocation textbox.
If you want to show it when page loads, just move your code in to Page_Load event instead uiToLocation_Leave.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
this.uiDistance.Text = "123"; // it will assign when page loads.
}
If you want to load it only once when page loads, use IsPostaback, see below.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
if (!IsPostBack)
{
this.uiDistance.Text = "123"; // it will assign only once when page loads.
}
}
IT seems you are using the wrong property to assign value to telerik Textbox.
Use .Value property as .Text property if for default aspx Textbox control
this.uiDistance.Value= "123"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyWeb.Data;
using MyWeb.Common;
using MyWeb.Business;
using AjaxPro;
using System.Text;
<asp:DataList ID="DataList1" runat="server" RepeatLayout="Flow">
<ItemTemplate>
<div class="m_status">
<div class="ava">
<a href="#">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("AvatarUS") %>'
CssClass="ava_medium"/></a>
</div>
<div class="sta_content">
<div class="sta_title">
<p class="sta_detail">
<asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Detail") %>'></asp:Literal>
</p>
<div class="function">
<a class="sta_like left" href="#">Thích</a>
<a class="sta_cmt left" href="#">Bình luận</a>
<a class="sta_share left" href="#">Chia sẻ</a>
</div>
</div>
</div>
</div>
</ItemTemplate>
</asp:DataList>
I want to add a DataList like that in code behind(Default.aspx.cs)
How to make it?
In the row databound event of the data list you can add some control that will hold the place for the control that you want to add, example:
In the ItemTemplate add one control to hold the control that will be addeded.
<asp:Panel runat="server" ID="pnlPlaceHolder">
<!-- the control will be added here -->
</asp:Panel>
and in code behind, on RowDataBound of the data list do the following
Panel pnlPlaceHolder = (Panel)e.Item.FindControl("pnlPlaceHolder");
if (pnlPlaceHolder!= null)
{
// The new control, a button, by example
Button btn = new Button();
btn.Text = "Added dinamically";
pnlPlaceHolder.Controls.Add(btn);
}
This is it.
Problem when I add in code behide: Default.aspx.cs
namespace KetBanBonPhuong
{
[AjaxPro.AjaxNamespace("Default")]
public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(Default1));
if(!isPostBack)
{
DataList dl = new DataList();
dl.DataSource = GetList();
dl.DataBind();
this.liststatus.Controls.Add(dl);
dl.DataSource = GetList();
dl.RepeatLayout = RepeatLayout.Flow;
Literal ltr = new Literal();
ltr.Text = "kaldfs";
dl.Controls.Add(ltr);//Error here
}
}
}
before I begin, there is another question with a similar title and it is unsolved but my situation is pretty different since I am using Ajax.
I recently added a label to my Ajax UpdateProgress control and for some reason my asp.net page is not reading it. My original goal was for the text of the label to be constantly be updating while the long method runs. I am using code behind, and I believe the label is declared. I will post my .cs page if anyone would like to read through it (its not too long), All my other labels work perfectly and even if I take the label OUT of the ajax control it will work fine (not the text updates though). Is there a certain Ajax label I need to use?
Im pretty confused why the error is occurring. The exact error message states : "The name 'lblProgress' does not exist in the current context. Im using c#, ajax controls, a asp.net page, and visual studio. This program uploads a file to a client and stores the information in a database. If anyone can help I would really appreciate it. Thanks in advance!
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Threading;
public partial class SendOrders : System.Web.UI.Page
{
protected enum EDIType
{
Notes,
Details
}
protected static string NextBatchNum = "1";
protected static string FileNamePrefix = "";
protected static string OverBatchLimitStr = "Batch file limit has been reached. No more batches can be processed today.";
protected void Page_Load(object sender, EventArgs e)
{
Initialize();
}
protected void Page_PreRender(object sender, EventArgs e)
{
}
protected void Button_Click(object sender, EventArgs e)
{
PutFTPButton.Enabled = false;
lblProgress.Visible = true;
lblProgress.Text = "Preparing System Checks...";
Thread.Sleep(3000);
Button btn = (Button)sender;
KaplanFTP.BatchFiles bf = new KaplanFTP.BatchFiles();
KaplanFTP.Transmit transmit = new KaplanFTP.Transmit();
if (btn.ID == PutFTPButton.ID)
{
lblProgress.Text = "Locating Files...";
//bf.ReadyFilesForTransmission();
DirectoryInfo dir = new DirectoryInfo(#"C:\Kaplan");
FileInfo[] BatchFiles = bf.GetBatchFiles(dir);
bool result = transmit.UploadBatchFilesToFTP(BatchFiles);
lblProgress.Text = "Sending Files to Kaplan...";
if (!result)
{
ErrorLabel.Text += KaplanFTP.errorMsg;
return;
}
bf.InsertBatchDataIntoDatabase("CTL");
bf.InsertBatchDataIntoDatabase("HDR");
bf.InsertBatchDataIntoDatabase("DET");
bf.InsertBatchDataIntoDatabase("NTS");
List<FileInfo> allfiles = BatchFiles.ToList<FileInfo>();
allfiles.AddRange(dir.GetFiles("*.txt"));
bf.MoveFiles(allfiles);
lblProgress.Text = "Uploading File Info to Database...";
foreach (string order in bf.OrdersSent)
{
OrdersSentDiv.Controls.Add(new LiteralControl(order + "<br />"));
}
OrdersSentDiv.Visible = true;
OrdersInfoDiv.Visible = false;
SuccessLabel.Visible = true;
NoBatchesToProcessLbl.Visible = true;
BatchesToProcessLbl.Visible = false;
PutFTPButton.Enabled = false;
BatchesCreatedLbl.Text = int.Parse(NextBatchNum).ToString();
Thread.Sleep(20000);
if (KaplanFTP.errorMsg.Length != 0)
{
ErrorLabel.Visible = true;
SuccessLabel.Visible = false;
ErrorLabel.Text = KaplanFTP.errorMsg;
}
}
}
Here is my aspx code as well.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SendOrders.aspx.cs" Inherits="SendOrders" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Kaplan EDI Manager</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.style1
{
width: 220px;
height: 19px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="mainPanel">
<div>
<h3>Number of Batches Created Today: <asp:Label runat="server" style="display:inline;" ID="BatchesCreatedLbl"></asp:Label>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<span class="red">COUNTDOWN TO SUBMISSION!</span>
<span id="timespan" class="red"></span>
</h3>
</div>
<div id="batchestoprocessdiv">
</div>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="BatchesToProcessLbl" runat="server" CssClass="green"
Height="22px" Text="THERE IS AN ORDER BATCH TO PROCESS."></asp:Label>
<asp:Label ID="NoBatchesToProcessLbl" runat="server" CssClass="red"
Text="There are no Order Batches to Process." Visible="false"></asp:Label>
<asp:Button ID="PutFTPButton" runat="server" onclick="Button_Click"
Text="Submit Orders" />
<asp:Label ID="SuccessLabel" runat="server" CssClass="green"
Text="Batch has been processed and uploaded successfully." Visible="false"></asp:Label>
<asp:Label ID="ErrorLabel" runat="server" CssClass="red" Text="Error: "
Visible="false"></asp:Label>
<asp:Label ID="lblProgress" runat="server" CssClass="green" Height="16px"
Text="Label" Visible="False"></asp:Label>
<br />
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
<br />
<img alt="" class="style1" src="images/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</div>
<div id="OrdersInfoDiv" runat="server" visible="false">
<asp:GridView ID="BatchDetails" Caption="Details of orders ready to be sent" runat="server" AutoGenerateColumns="true"
CssClass="InfoTable" AlternatingRowStyle-CssClass="InfoTableAlternateRow" >
</asp:GridView>
</div>
<div id="OrdersSentDiv" class="mainPanel" runat="server" visible="false">
<h4>Sent Orders</h4>
</div>
</form>
<script src="js/SendOrders.js" type="text/javascript"></script>
</body>
</html>
If the Label is created inside the UpdateProgress control, then you will need to do something like this
((Label)upUpdateProgress.FindControl("lblProgress")).Text = "Uploading File...";
If the control is declared in markup and the code-behind doesn't recognize it, then your designer.cs file is probably out of sync. There are a few ways to fix this:
Close the form and reopen it, and remove and add lblProgress again
Add the Label to the designer.cs file manually
Here's how to add it manually:
/// <summary>
/// lblProgress control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblProgress;
EDIT
Just noticed that you're putting the UpdatePanel in an UpdateProgress control, in which case you'll need to reference it using FindControl (like #Valeklosse) suggested.
I have the following asp.net page
<form id="form1" runat="server">
<asp:Button id="display_button" runat="server" Text="Display" OnClick="Button1_Click" />
<asp:Button id="edit_button" runat="server" Text="Edit" OnClick="Button2_Click" />
<asp:Button id="save_button" runat="server" Text="Save" OnClick="Button3_Click" Visible="false" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:MultiView id="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View id="View1" runat="server">
<asp:FormView id="view_program" runat="server">
<ItemTemplate>
<tr>
<td class="add_border_bold" nowrap">Status</td>
<td width="100%" class="add_border">
<img src="images/<%# Eval("status").ToString().Trim() %>_light_16.gif" alt="status" />
</td>
</tr>
<tr>
<td class="add_border_bold" nowrap">Short Title</td>
<td width="100%" class="add_border">
<%# Eval("short_title") %>
</td>
</tr>
</ItemTemplate>
</asp:FormView>
</asp:View>
<asp:View id="View2" runat="server">
<asp:FormView id="edit_program" runat="server">
<ItemTemplate>
<tr>
<td class="add_border_bold"nowrap">Status </td>
<td width="100%" class="add_border">
<asp:DropDownList id="p_status" runat="server"></asp:DropDownList>
</td>
</tr>
<tr>
<td class="add_border_bold" nowrap">Short Title</td>
<td width="100%" class="add_border">
<asp:TextBox runat="server" id="short_title" />
</td>
</tr>
</ItemTemplate>
</asp:FormView>
</asp:View>
</form>
with the following code behind page
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
namespace TM_non_deploy
{
public partial class Program : System.Web.UI.Page
{
protected Label Label1;
protected Person myPerson;
protected TestProgram myProgram;
List<TestProgram> program = null;
protected void Page_Load(object sender, EventArgs e)
{
try
{
myPerson = new Person("user");
myProgram = new TestProgram("999");
//needs to be done to refresh info on page
program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
if (!IsPostBack)
{
//create controls and bind data
edit_program.DataSource = program;
edit_program.DataBind();
DropDownList p_status = edit_program.FindControl("p_status") as DropDownList;
p_status.Items.Add(new ListItem("Green"));
p_status.Items.Add(new ListItem("Yellow"));
p_status.Items.Add(new ListItem("Red"));
p_status.SelectedValue = myProgram.Status.Trim();
TextBox short_title = edit_program.FindControl("short_title") as TextBox;
short_title.Width = 200;
short_title.Text = myProgram.Short_Title.Trim();
}
}
catch (Exception ex)
{
Response.Write(ex);
Label1.Text = ex.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
protected void Button2_Click(object sender, EventArgs e)
{
MultiView1.SetActiveView(View2);
save_button.Visible = true;
}
protected void Button3_Click(object sender, EventArgs e)
{
DropDownList c_status = edit_program.FindControl("p_status") as DropDownList;
myProgram.Status = c_status.SelectedValue;
bool update = myProgram.SaveTestProgram();
if (update)
{
Label1.Text = "Saved!";
//needs to be done to refresh info on page
program = new List<TestProgram> { myProgram };
view_program.DataSource = program;
view_program.DataBind();
MultiView1.SetActiveView(View1);
save_button.Visible = false;
}
else
{
Label1.Text = "Error Saving";
}
}
}
}
basically, it is one page that both displays the fields, and then on a button click displays the editable version of all those fields. my question is, should i be displaying all of the information like i am now, with evals? or should i switch to labels, or literals, or something else entirely? i want to know before i get too far and have to undo a lot of work.
there will end up being a ton of fields on this page, all types from checkboxes to dropdowns to multiline textboxes, so i want to make sure i pick the path that works best for displaying all of those different kinds of data, even though in this example i am only displaying small text information.
If you just need to display text, there's no reason not to just use your <%# Eval("title") %>
One thing that should be noted though, is that it's better to cast your DataItem and access the properties that way instead of Eval as Eval has to use reflection and is more costly (maybe to the being of actually being noticeable if you have a lot of stuff repeated).
Use: <%# (Container.DataItem as SomeObject).Title %> instead of <%# Eval("Title") %>
Kind of outside the scope of your question but just a side note. :)
I wouldn't go for ServerSide Controls (Labels/Literals) unless you need formatting or to change the control values in other server side events. They just add to ViewState (unless ViewState is disabled on those Controls).
Coming to whether it's the right approach, I would suggest you use EditItemTemplate of FormView instead of 2 FormViews in Different Views & a MultiView Control!