how to set contol property in asp.net - c#

Very simple and stupid question.
i have a page class
public partial class ProtectWayItem : System.Web.UI.UserControl
{
public int Count { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Count = 10;
}
}
and how i can set div id equal Count.
I mean something like:
<div id='<%# Count %>' > </div>

You have to use = instead #
<div id='<%= Count %>' >
And if you want to call with the # sign then you need to call a DataBind() method..
protected void Page_PreRenderComplete(object sender, EventArgs e)
{
DataBind();
}
here is what each expression means
The <%= expressions are evaluated at
render time
The <%# expressions are evaluated at
DataBind() time and are not evaluated
at all if DataBind() is not called.
<%# expressions can be used as
properties in server-side controls.
<%= expressions cannot.
For a better understanding, please check out this link: The difference between <%= and <%# in ASP.NET

<div id='<%= Count %>' > </div>
But you must remember this section must be in FORM section.

Related

Multiview controls

I wrote the following code for multiview where I am using gridview and datalist:
<ContentPlaceHolderID="ContentPlaceHolder1">
<div class="alert alert-success" >
<div class="divbtn" style="text-align:right">
<asp:LinkButton ID="gridbtn" runat="server" CssClass="glyphicon glyphicon-th" OnClick="gridbtn_Click"></asp:LinkButton>
<asp:LinkButton ID="listbtn" runat="server" CssClass="glyphicon glyphicon-th-list" OnClick="listbtn_Click"></asp:LinkButton>
</div>
</div>
<asp:MultiView runat="server" ID="multiview" ActiveViewIndex="0">
<asp:View runat="server" ID="gridview">
<uc1:GridControl runat="server" ID="GridControl"/>
</asp:View>
<asp:View runat="server" ID="listview">
<uc1:Listing runat="server" ID="Listing" />
</asp:View>
</asp:MultiView>
</asp:Content>
I am using two link buttons to call their respective views by firing two separate events as follows.
protected void listbtn_Click(object sender, EventArgs e)
{
multiview.ActiveViewIndex = 1;
}
protected void gridbtn_Click(object sender, EventArgs e)
{
multiview.ActiveViewIndex = 0;
}
Suppose, my datalist (Index=1) is active on my page and if there is a post back it should still be showing the datalist but on postback it automatically switches back to grid view (Index=0). I really need help with this!
You can save the index to a session variable and then read it back on post back like this:
To save:
Session["index"] = index.ToString();
Read it on page load like this:
Index = Session["index"];
You will need the session variable to maintain state per user session. If you want to maintain state for the application then you have to use the application variable.
Hi add the following code in your page_load event.
if(!Page.IsPostBack)
{
multiview.ActiveViewIndex=0;
}
i think you are setting the multiview's active index to zero on every post back like follows
protected void Page_Load(object sender, EventArgs e)
{
multiview.ActiveViewIndex=0;
}
this will cause the multiview to set active index as 0 on every post back.To avoid this you have to set it as follows
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
multiview.ActiveViewIndex=0;
}
}

Eval in anchor href

I have the following code behind:
protected string VcdControlPanelLink { get; set; }
protected void Page_Load(object sender, EventArgs e) {
VcdControlPanelLink = "http://www.mywebsite.com";
}
And the following markup:
VDC control panel
But when I run the page, the href tag is rendered as an empty string:
<a title="View the VDC control panel" target="_blank" href="">VDC control panel</a>
I have tried various combinations of markup etc, but cannot get it to work. What am i missing?
If you use data binding expressions <%# ... %> in templates (e.g. the ItemTemplate of a GridView), data binding is invoked automatically. However, if you use such expressions outside of templates, you need to invoke data binding yourself by calling Control.DataBind() (or this.DataBind() in your case):
protected string VcdControlPanelLink { get; set; }
protected void Page_Load(object sender, EventArgs e) {
VcdControlPanelLink = "http://www.mywebsite.com";
this.DataBind();
}
<!-- Note that you do *not* use Eval here! -->
<a href='<%# VcdControlPanelLink %>' target="_blank" ... />
However, I don't think data binding is the right tool here. Since you are using basic HTML elements (instead of web controls), you can just use an inline ASP.NET expression (no this.DataBind() required):
<a href='<%= VcdControlPanelLink %>' target="_blank" ... />
In any case, make sure your link does not contain quotes ', or you are in for some HTML injection. If the value is supplied by the user, don't forget to HtmlEncode and sanitize it.
Make your property public and access it like this,
public string VcdControlPanelLink { get; set; }
VDC control panel

Viewstate is null on postback

Right, I've got something very peculiar going on here...
ASP.NET 4 page with the following property:
protected QuickShopBag QuickShopBagInstance
{
get { return (QuickShopBag)ViewState["QuickShopBag"]; }
set { ViewState["QuickShopBag"] = value; }
}
During the initial Page_Load() in (!Page.IsPostBack) the QuickShopBagInstance is populated and ViewState saved.
However when you perform a postback on the page the ViewState is empty when accessed from the postback Button_OnClick() event!!!
I've checked the Request.Form and sure enough the _Viewstate value is there and is populated. I've also ran this value through a parser and it does contain the expected data, the page has ViewStateEnabled="true" and the new .NET 4 ViewStateMode="Enabled".
I've moved on to override the LoadViewState method to check to see if it is firing, it doesn't appear to be.
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
I am really lost as to what could possibly be the problem. Any ideas?
First of all I was mistaken, the code in question was not in Page_Load but in Page_Init, although I haven't read anything that says you can't assign to ViewState at Init.
So I put together a very basic test that duplicates the problems I'm having...
<form id="form1" runat="server">
<div>
<asp:ListView id="QuickshopListView" runat="server">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<asp:TextBox ID="txtItem" runat="server" Text='<%# Container.DataItem %>' />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
<br />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
</div>
</form>
public partial class Quickshop : System.Web.UI.Page
{
protected QuickShopBag QuickShopBagInstance
{
get { return (QuickShopBag)ViewState["QuickShopBag"]; }
set { ViewState["QuickShopBag"] = value; }
}
protected void Page_Init(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (QuickShopBagInstance == null)
QuickShopBagInstance = new QuickShopBag();
if (!String.IsNullOrEmpty(Request.QueryString.ToString()))
{
string[] items = Server.UrlDecode(Request.QueryString.ToString()).Split(',');
if (items.Length > 0)
{
foreach (string item in items)
{
QuickShopBagInstance.QuickShopItems.Add(item);
}
}
}
}
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
QuickshopListView.DataSource = QuickShopBagInstance.QuickShopItems;
QuickshopListView.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
if (QuickShopBagInstance == null)
QuickShopBagInstance = new QuickShopBag();
QuickShopBagInstance.QuickShopItems.Add("add1");
QuickShopBagInstance.QuickShopItems.Add("add2");
QuickShopBagInstance.QuickShopItems.Add("add3");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
Button DeleteButton = (Button)sender;
ListViewDataItem item = (ListViewDataItem)DeleteButton.NamingContainer;
QuickShopBagInstance.QuickShopItems.RemoveAt(item.DisplayIndex);
}
}
[Serializable]
public class QuickShopBag
{
public List<string> QuickShopItems { get; set; }
public QuickShopBag()
{
this.QuickShopItems = new List<string>();
}
}
If you request say "/quickshop.aspx?add1,add2,add3", the ListView is populated correctly with the data from the qs, however when it comes to clicking the delete button a NullReferenceException is thrown because the ViewState hasn't persisted the QuickShopBag object.
But if you click the "Add" button, which as you can see adds to the same values to the QuickShopBagInstance (and ViewState), the ListView is populated correctly and when you click the Delete button it works perfectly as the ViewState has been persisted.
Now if you change the reading the querystring bit to Page_InitComplete as opposed to Page_Init it works perfectly. So the conclusion is...
YOU CAN'T ADD TO THE VIEWSTATE BEFORE Init_Complete!!!!!!!!
How silly of me, well whoever wrote it at least!
You seem to have ruled out most of the suggestions so far so I've created a basic page with only the information you've provided above:
class
namespace SO_Questions
{
[Serializable()]
public class QuickShopBag
{
public string MyProperty { get; set; }
}
}
code behind
namespace SO_Questions
{
public partial class TestPage : System.Web.UI.Page
{
protected QuickShopBag QuickShopBagInstance
{
get { return (QuickShopBag)ViewState["QuickShopBag"]; }
set { ViewState["QuickShopBag"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.QuickShopBagInstance = new QuickShopBag() { MyProperty = "Test String" };
}
Message.Text = "Value is: " + this.QuickShopBagInstance.MyProperty.ToString();
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
btnSubmit.Text += QuickShopBagInstance.MyProperty;
}
}
}
markup:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="TestPage.aspx.cs" Inherits="SO_Questions.TestPage" ViewStateMode="Enabled" %>
<!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 runat="server"><title></title></head>
<body>
<form id="form1" runat="server"><div>
<asp:Label ID="Message" runat="server"></asp:Label>
<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" />
</div></form>
</body></html>
As expected, this runs correctly; the overridden LoadViewState method is hit (and viewstate correctly contains 2 items) and the button's text is updated.
The logical explanation would be that there's something else going on somewhere else, or you've failed to provide an additional salient piece of information.
Something that has tripped me up in the past is
Setting something in the ViewState in the page
Then trying to retrieve it in a user control. Can't find it - where has it gone?
It seems as if you should have one ViewState per page but each usercontrol keeps it's own version.
Could it be something like this?
This SO link gives a better explanation that I have just done
Just a quick note. If you are setting a ViewState value on page_load, make sure you are doing it wrapped in
if (!IsPostBack)
{
ViewState["MyValue"] = MyValue // set dynamically with appropriate code
}
If you don't do this and you do a postback...but your code setting this ViewState value is not in the !IsPostBack brackets, it will reset your ViewState value to null every time you do a postback, no matter where you enable ViewState on the page.
This may seem obvious, but it is easy to miss if you have a lot of code going on.
Or I guess you could not use !IsPostBack if you want your code to run on every postback. But if you are having trouble with a value getting set to null on postback, examine the above carefully.

C# - Reload tabs from Master page

I have a FromDate and ToDate textboxes and a submit button in my Master page. I have 4 tabs with links for 4 different URLs displaying various reports.
Now on change of Dates and click of submit button, can I update/reload the reports (tabs) based on date change?
Thanks a lot in advance :)
I would suggest moving your from-to dates and submit button to a user control. You can then put that on each report, expose and wire up changed events on your control and expose properties for your from-to date textboxes to pop into your report.
In Visual Studio create a user control. If you are unsure how to do this try this link.
Populate the user control with your text boxes. Something like this:
<div>
<asp:Label ID="FromDateLabel" Text="From:" AssociatedControlID="FromDateTextBox" runat="server" />
<asp:TextBox ID="FromDateTextBox" runat="server" />
<asp:Label ID="ToDateLabel" Text="To:" AssociatedControlID="ToDateTextBox" runat="server" />
<asp:TextBox ID="ToDateTextBox" runat="server" />
<asp:Button ID="UpdateButton" Text="Update" runat="server"
onclick="UpdateButton_Click" />
</div>
And the code behind for that control. You'll need to expose an event and the two properties, which might look like this:
public partial class ReportDateControl : System.Web.UI.UserControl
{
public event EventHandler UpdateReport;
public string FromDate
{
get { return this.FromDateTextBox.Text; }
set { this.FromDateTextBox.Text = value; }
}
public string ToDate
{
get { return this.ToDateTextBox.Text; }
set { this.ToDateTextBox.Text = value; }
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
if (UpdateReport != null)
{
UpdateReport(this, EventArgs.Empty);
}
}
}
In your .aspx page you'll need to register the control, which might go something like this:
<%# Register Src="~/Controls/ReportDateControl.ascx" TagPrefix="myapp" TagName="ReportDateControl" %>
And then actually put it on the page:
<myapp:ReportDateControl id="ReportDateControl"
runat="server"
OnUpdateReport="ReportDateControl_UpdateReport" />
And then wire up the code behind to handle the update events:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ReportDateControl_UpdateReport(object sender, EventArgs e)
{
Controls.ReportDateControl control = (Controls.ReportDateControl)sender;
string fromDate = control.FromDate;
string toDate = control.ToDate;
}
}
Change the names and formatting where appropriate, but this should give you a good idea.
Also, you can expose the Date controls from the master page and access them through the Page.Master property. You'll need to cast to the specific type of your master page to get at it's properties.

Anchor control in Literal

using System;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
public void Download(object obj, EventArgs e)
{
Response.Write("abc");
}
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Text = "<a id='anc' href ='#' runat='server' onserverclick='Download'>Click Me</a>";
Response.Write(Literal1.Text);
}
}
}
<div>
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
I have the above code sniplet. I am trying to bind the anchor within the literal to a function in a following manner: onserverclick = "Download"
But the event is not firing. The requirement is that anchor is rendered through literal only.
Please help.
While your Literal1 control is a server-side control, setting the .Text value to represent a server control will not work.
Perhaps use the asp LinkButton control instead of a literal
so your .aspx page would have:
<asp:LinkButton ID="abc" runat="server" OnClick="Download" Text="Download" />
and your code behind .aspx.cs something like:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Download(object sender, EventArgs e)
{
Response.Write("abc");
}
The attribute runat="server" is meaningless in the client-side code (which is what you're generating here). You may need to resort to calling a webservice.
We are using anchor tag outside literal. Then it works fine
If you do not wish to use a LinkButton, you could replace your Literal with the text which you are adding to it on Page_Load (not entirely sure why youre doing it this way anyway?).
And then run an AJAX web request to run the Download method.

Categories

Resources