I have the following code, in which I am trying to transfer some text in a previous page's textbox control (located in the master page) to the same master page textbox control. However it is not working. Please let me know if you can spot the error.
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox placeholder =
(TextBox)PreviousPage.Master.FindControl("TextBox1");
if (placeholder != null)
{
TextBox searchBox = (TextBox)Master.FindControl("TextBox1");
string search = placeholder.Text.ToString();
searchBox.Text = search;
}
}
}
this is the .aspx of the master page:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="AlexBookShop.Site1" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<asp:ContentPlaceHolder ID="head" runat="server">
</asp:ContentPlaceHolder>
<style type="text/css">
.auto-style1 {
margin-bottom: 0px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Children</asp:ListItem>
<asp:ListItem Value="1">Finance</asp:ListItem>
<asp:ListItem Value="3">Non-Fiction</asp:ListItem>
<asp:ListItem Value="4">Technical</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" CssClass="auto-style1"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Search" OnClick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Log Out" OnClick="Button2_Click" />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
For transferring data from one page to other page via MasterPAge you need to do cross page posting.
you need to assign the PostBackUrl property of a button control on the first page to point to the second one. like
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/Secondpage.aspx"/>
set the PreviousPage directive on the second page:
<%# PreviousPageType VirtualPath="~/firstpage.aspx" %>
Then whenever second page receives a postback, get the data you need from the first page:
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
TextBox placeholder =
(TextBox)PreviousPage.Master.FindControl("TextBox1");
if (placeholder != null)
{
TextBox searchBox = (TextBox)Master.FindControl("TextBox1");
string search = placeholder.Text.ToString();
searchBox.Text = search;
}
}
}
Related
I have a 'LinkButton' in GridView. when click on it, I want to popup a window. so when I click the linkbutton, onClientClick triggers first. but I want to wait the hidden field value being set in code behind, then pass the hidden value as an arg of my popup window.but now, the hidden field value is always null. So how can I make this work? Thanks.
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
// load something
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
//set hidden feild value
hdfilename.Value = "something";
}
</script>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function GetSelectedRow(sender) {
if (!sender) return;
var hrefToEvalWhenFinished = sender.attributes['href'].value; // Ext.get(sender).getAttribute('href');
if (hrefToEvalWhenFinished) {
// todo: do async work here
// Fire the links HREF event which will do the postback.
eval(hrefToEvalWhenFinished);
var filename = document.getElementById("<% =hdfilename.ClientID %>").value;
if (filename) {
window.open('/Blank.aspx?f=filename', 'popUpWindow', 'height=500,width=400,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkSelect" runat="server" Text='<%# Eval("Description") %>' CommandArgument='<%# Container.DataItemIndex %>' CommandName="ViewDocument" OnClientClick="return GetSelectedRow(this);" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:HiddenField ID="hdfilename" runat="server" />
</form>
</body>
</html>
I'm testing out some code that calculates the days by subtracting 2 dates and posting back the number of days in between.
Here is the first test:
CalculateDaysTest1.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CalculateDaysTest1.aspx.cs" Inherits="PopeyeMarinaWebApp.Templates.CalculateDaysTest1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Calculate Dates Test 1</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div class="formitem">
<asp:Label ID="startDateLabel" CssClass="formlabel" runat="server" Text="Start Date:"></asp:Label>
<asp:TextBox ID="txtStartDate" CssClass="DatePicker" runat="server" AutoPostBack="True" OnTextChanged="calculateDays"></asp:TextBox>
</div>
<div class="formitem">
<asp:Label ID="endDateLabel" CssClass="formlabel" runat="server" Text="End Date:"></asp:Label>
<asp:TextBox ID ="txtEndDate" CssClass="DatePicker" runat="server" AutoPostBack="True" OnTextChanged="calculateDays"></asp:TextBox>
</div>
<div class="formitem">
<asp:Label ID="totalDaysLabel" CssClass="formlabel" runat="server" Text="Number of Days:"></asp:Label>
<asp:Label ID="totalDays" CssClass="idlabel" runat="server" Text=""></asp:Label>
</div>
</div>
<script>
$(function () {
$('.DatePicker').datepicker(
{
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1950:2100'
});
})
</script>
</form>
</body>
</html>
CalculateDaysTest1.cs
using System;
namespace PopeyeMarinaWebApp.Templates
{
public partial class CalculateDaysTest1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void calculateDays(object sender, EventArgs e)
{
string startdate = txtStartDate.Text;
string enddate = txtEndDate.Text;
if (startdate != "" && enddate != "")
{
DateTime t1 = Convert.ToDateTime(startdate);
DateTime t2 = Convert.ToDateTime(enddate);
totalDays.Text = t2.Subtract(t1).Days.ToString();
}
}
}
}
Everything here is working perfectly and it's doing what it's supposed to be doing. You can select the start and end date and it posts back the calculated days.
Now for the second test I'm using it in the context of a Form View Control using model binding.
Here is Test 2:
CalculateDaysTest2.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CalculateDaysTest2.aspx.cs" Inherits="PopeyeMarinaWebApp.Templates.CalculateDaysTest2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Calculate Dates Test 2</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FormView ID="FormView1" runat="server"
ItemType="PopeyeMarinaWebApp.Models.Lease"
DataKeyNames="LeaseID"
RenderOuterTable="false"
DefaultMode="Insert"
InsertMethod="LeaseFormAdd_InsertItem">
<InsertItemTemplate>
<fieldset>
<div class="formitem">
<asp:Label ID="startDateLabel" CssClass="formlabel" runat="server" Text="Start Date:"></asp:Label>
<asp:TextBox ID="txtStartDate" CssClass="DatePicker" runat="server" AutoPostBack="True" OnTextChanged="calculateDays" Text="<%#: BindItem.StartDate %>"></asp:TextBox>
</div>
<div class="formitem">
<asp:Label ID="endDateLabel" CssClass="formlabel" runat="server" Text="End Date:"></asp:Label>
<asp:TextBox ID ="txtEndDate" CssClass="DatePicker" runat="server" AutoPostBack="True" OnTextChanged="calculateDays" Text="<%#: BindItem.EndDate %>"></asp:TextBox>
</div>
<div class="formitem">
<asp:Label ID="totalDaysLabel" CssClass="formlabel" runat="server" Text="Number of Days:"></asp:Label>
<asp:Label ID="totalDays" CssClass="idlabel" runat="server" Text=""></asp:Label>
</div>
<div class="col-lg-12">
<asp:Button ID="InsertButton" runat="server" Text="Insert" CausesValidation="True" CssClass="btn btn-primary btn-sm" CommandName="Insert" />
<asp:Button ID="CancelButton" runat="server" Text="Cancel" CssClass="btn btn-primary btn-sm" CommandName="Cancel"/>
</div>
</fieldset>
</InsertItemTemplate>
</asp:FormView>
</div>
<script>
$(function () {
$('.DatePicker').datepicker(
{
dateFormat: 'dd/mm/yy',
changeMonth: true,
changeYear: true,
yearRange: '1950:2100'
});
})
</script>
</form>
</body>
</html>
CalculateDaysTest2.cs
using System;
using PopeyeMarinaWebApp.Models;
namespace PopeyeMarinaWebApp.Templates
{
public partial class CalculateDaysTest2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void LeaseFormAdd_InsertItem()
{
var item = new Lease();
TryUpdateModel(item);
if (ModelState.IsValid)
{
using (MarinaDBContext db = new MarinaDBContext())
{
db.Leases.Add(item);
db.SaveChanges();
}
}
}
protected void calculateDays(object sender, EventArgs e)
{
string startdate = txtStartDate.Text;
string enddate = txtEndDate.Text;
if (startdate != "" && enddate != "")
{
DateTime t1 = Convert.ToDateTime(startdate);
DateTime t2 = Convert.ToDateTime(enddate);
totalDays.Text = t2.Subtract(t1).Days.ToString();
}
}
}
}
Here I'm getting an error in the calculateDays event which says:
'The name 'textStartDate' does not exist in the current context'
'The name 'textEndDate' does not exist in the current context'
'The name 'totalDays' does not exist in the current context'
I'm just wondering why this doesn't work within a Form View control and how can I fix it.
Any help would be much appreciated.
David
You've placed your code inside an "asp:FormView", which is preventing you from accessing your TextBox's etc directly in the code behind.
You'll need to setup something to handle commands from your FormView. In the code behind, you'll need something like this - although the example below is written off the top of my head.
void FormView1_ItemCommand(Object sender, FormViewCommandEventArgs e)
{
TextBox txtStartDate = (TextBox)e.Item.FindControl("txtStartDate");
if (e.CommandName == "Insert")
{
// Your logic here
}
}
Note you need to connect this code using the "OnItemCommand" property of your FormView on the aspx page.
See the MSDN documentation for a more extensive example.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.formview.itemcommand(v=vs.110).aspx
As for accessing the TextBox's anywhere in the code behind, you'll need to use the FindControl method on the FormView. Something like one of these:
TextBox txtStartDate = (TextBox)FormView1.Row.FindControl("txtStartDate");
Or
TextBox txtStartDate = (TextBox)FormView1.InsertItem.FindControl("txtStartDate");
I get an "Object reference not set to an instance of an object." error on the line "welcome.Text = ...."
Home:
protected void OKButton_Click(object sender, EventArgs e)
{
if (UserNameTextBox.Text != String.Empty)
{
Session["UserName"] = UserNameTextBox.Text;
Label welcome = (Label)Master.FindControl("GreetingLabel");
welcome.Text = String.Format("Welcome, {0}!", Session["UserName"]);
}
}
<%# Page Title="" Language="C#" MasterPageFile="~/Professional.master" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home"%>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
<br /><br />
<asp:TextBox ID="UserNameTextBox" runat="server"></asp:TextBox>
<br /><br />
<asp:DropDownList ID="SitePrefDropDownList" runat="server" AutoPostBack="True">
<asp:ListItem Text="Professional" Value="Professional"></asp:ListItem>
<asp:ListItem Text="Colourful" Value="Colourful"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<asp:Button ID="OKButton" runat="server" Text="OK" onclick="OKButton_Click" />
</asp:Content>
I got the code from MCTS Exam 70-515 Web Dev book.
I looked at the Errata page, no luck. http://oreilly.com/catalog/errataunconfirmed.csp?isbn=9780735627406
Master Page:
public partial class Professional : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["UserName"] != null)
{
GreetingLabel.Text = String.Format("Welcome, {0}!", Session["UserName"]);
}
}
}
<%# Master Language="C#" AutoEventWireup="true" CodeFile="Professional.master.cs" Inherits="Professional" %>
<!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>
<asp:ContentPlaceHolder id="HeadContent" runat="server">
</asp:ContentPlaceHolder>
<link href="~/Styles/Site.css" rel="Stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="Contoso.gif" /><asp:Label ID="Label1" runat="server" Text="Welcome to Contoso!"
Font-Size="X-Large"></asp:Label>
<asp:Menu ID="Menu1" runat="server" Orientation="Horizontal">
<Items>
<asp:MenuItem Text="Products" Value="Products"></asp:MenuItem>
<asp:MenuItem Text="Services" Value="Services"></asp:MenuItem>
<asp:MenuItem Text="Downloads" Value="Downloads"></asp:MenuItem>
<asp:MenuItem Text="About Us" Value="About Us"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:ContentPlaceHolder id="MainContent" runat="server">
<asp:Label ID="GreetingLabel" runat="server" Text="Label"></asp:Label>
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
Regards
LF
Where is the GreetingLabel control located in the master? If it's in a ContentPlaceHolder the NamingContainer is that not the master.
You: "it is in a Master, under":
<asp:ContentPlaceHolder id="MainContent" runat="server">
That's it, you first have to find the ContentPlaceHolder, then use FindControl on it:
var cPlaceHolder = (ContentPlaceHolder)Master.FindControl("MainContent");
Label welcome = (Label)cPlaceHolder.FindControl("GreetingLabel");
Now you don't get a NullReferenceException on welcome.Text anymore:
welcome.Text = String.Format("Welcome, {0}!", Session["UserName"]);
Edit Since you have commented that it still doesn't work for whatever reason. I will suggest a different - better - approach. Provide a public property in your Master, for example Greeetings. Then you can get/set the Label.Text via this property. That is much more readable and maintainable. It will also work even if you change the label to a different control like TextBox or Div.
For example (in the MasterPage of type Professional):
public string Greetings
{
get { return GreetingLabel.Text; }
set { GreetingLabel.Text = value; }
}
Now you can cast the Master property in your content-page to Professional to access it:
Professional professional = (Professional) this.Master;
professional.Greetings = String.Format("Welcome, {0}!", Session["UserName"]);
Try this:
see this
welcome.Text = String.Format("Welcome, {0}!", Session["UserName"]);// replace Session["UserName"] with Session["UserName"].ToString()
now your new line is
welcome.Text = String.Format("Welcome, {0}!", Session["UserName"].ToString());
Ok so I am trying to make a list of links in a page that is generated using a foreach and loop as long as there are objects in the list. Here is the code that I use to generate the links:
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["mamlist"] != null)
{
mamlist = (List<mammifere>)Session["mamlist"];
int i = 0;
foreach (mammifere l in mamlist)
{
mamol.InnerHtml += ("<li><a onClick='select("+i+");' >" + l.Nom + "</a></li>");
i++;
}
}
}
}
For some reason, the links are unclickable. I get this:
How can I make links that do not lead to another page but instead launch a method in the C# code of the page?
You can create LinkButton controls that call subroutines/methods in your ASPX code:
Sample code:
<%# Page Language="C#" AutoEventWireup="True" %>
<!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>
<title>LinkButton Example</title>
<script language="C#" runat="server">
void LinkButton_Click(Object sender, EventArgs e)
{
Label1.Text="You clicked the link button";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<h3>LinkButton Example</h3>
<asp:LinkButton id="LinkButton1"
Text="Click Me"
Font-Names="Verdana"
Font-Size="14pt"
OnClick="LinkButton_Click"
runat="server"/>
<br />
<asp:Label id="Label1" runat="server" />
</form>
</body>
</html>
In your specific case, add a ContentPlaceHolder in your master page:
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server" />
In the page where you want the links to appear you add a Content control like so:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
Then foreach link you want, do this:
foreach (mammifere l in mamlist)
{
LinkButton linkButton = new LinkButton();
linkButton.Text = l.Nom;
linkButton.OnClick= "LinkButton_Click";
linkButton.ID = l.Nom;
Content1.Controls.Add(linkButton);
}
I have a drop down and a div right next to it. The text contained inside the div should be updated based on value selected in the dropdown.
I do NOT want to use AutoPostBack feature.
Use OnChange client side event of the dropdownlist control. Here is a sample that updates a div's inner text with the selected value of the dropdown list :
<asp:DropDownList runat="server" ID="myDDL"
OnChange="document.getElementById('myDiv').innerText=this.value;">
</asp:DropDownList>
<div id="myDiv"></div>
As people have said, you cannot access the C# codebehind code without performing a postback.
One way of accomplishing what you want is to use PageMethods. This is the Microsoft idiom for accomplishing this but there are lots of other Ajax libraries that will do it.
Provide a static method in your codebehind which will get called form your dropdownlist OnChange event.
[WebMethod]
public static string MyMethod()
{
// Your code goes here
return "The text for the div"
}
You then call this PageMethod from your .aspx page:
You need to add a scriptmanager (after the form tag)
<asp:ScriptManager ID="scriptmanager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" ></asp:ScriptManager>
Then in the OnChange event (or a function called from it) you have:
<asp:DropDownList id="ddl" runat="server" OnChange="PageMethods.MyMethod(OnComplete);" />
Where OnComplete is a javascript function that handlers the PageMethod response:
<script language="javascript">
function OnComplete(result, userContext, methodName) {
document.getElementById(yourDivId').innerText=result;
}
</script>
You can also have a paramaterised webmethod if needed:
[WebMethod]
public static string MyMethod(string myNeatParam)
{
// Your code goes here
return "The text for the div"
}
And call it with:
PageMethods.MyMethod('SomeValue', OnComplete)
Updated based on comments:
Here's a sample page on using an UpdatePanel to do what you need to do. Please keep in mind though that there is a full postback happening, even though it is transparent to the user.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpdatePanelMadness._Default" %>
<!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:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ColorsDropDownList" runat="server" AutoPostBack="true"
onselectedindexchanged="ColorsDropDownList_SelectedIndexChanged">
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Green" Value="Green" />
<asp:ListItem Text="Blue" Value="Blue" />
</asp:DropDownList>
<div id="ColorDiv" runat="server">
<p>
Hello World!
</p>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
code behind:
namespace UpdatePanelMadness
{
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ColorsDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
ColorDiv.InnerText = this.ColorsDropDownList.SelectedValue;
}
}
}