Error on String.Format - asp.net

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());

Related

Value from previous page not transferring

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;
}
}
}

ASP.NET Code behind not recognising control ID, error 'The name does not exist in current context'

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");

Ext.Net: radiogruop ,make selected radiobutton depend on its InputValue

I have a radiogruop like this.
<ext:RadioGroup ID="rdyIsAktifmi" runat="server" FieldLabel="Aktifmi" Width="150"
Flex="1">
<Items>
<ext:Radio ID="Radio4" runat="server" BoxLabel="pasif" InputValue="0" />
<ext:Radio ID="Radio5" runat="server" BoxLabel="aktif" InputValue="1" />
</Items>
</ext:RadioGroup>
I save the cheched input value like this,
rdyIsAktifmi.CheckedItems[0].InputValue //0 or one depents on cheched item
however when binding it from code behind I failed.
I tryed this one :
rdyIsAktifmi.CheckedItems[0].Values = employee_obj.IsAktif;(this come from database as integer value)
I also tried this one :
rdyIsAktifmi.CheckedItems[0].Set("rdyIsAktifmi", employee_obj.IsAktif);
how I can select radiobutton depents on its InputValue.
**what I exactly looking for a methot something like this.
rdyIsAktifmi.CheckedItem.InputValue=employee_obj.IsAktif;
thank you .
I would achieve it this way.
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<%# Import Namespace="System.Linq" %>
<script runat="server">
protected void Set0(object sender, DirectEventArgs e)
{
Radio r = this.RadioGroup1.Items.Cast<Radio>().First<Radio>(item => item.InputValue == "0");
r.Checked = true;
}
protected void Set1(object sender, DirectEventArgs e)
{
Radio r = this.RadioGroup1.Items.Cast<Radio>().First<Radio>(item => item.InputValue == "1");
r.Checked = true;
}
</script>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
<ext:RadioGroup ID="RadioGroup1" runat="server" ColumnsNumber="1">
<Items>
<ext:Radio ID="Radio1" runat="server" BoxLabel="off" InputValue="0" />
<ext:Radio ID="Radio2" runat="server" BoxLabel="on" InputValue="1" />
</Items>
</ext:RadioGroup>
<ext:Button runat="server" Text="Set 0" OnDirectClick="Set0" />
<ext:Button runat="server" Text="Set 1" OnDirectClick="Set1" />
</form>
</body>
</html>

How to fire direct event in row editing in gridpanel in ext.net

i'm using VB.net with ext.net (version 1.6).
i have a Gridpanel where i can double click on a row in order to edit it.
I can successfully edit it, but i need a direct event to be called whenever i finish editing ( in order to update the row in my database ).
I tried :
<ext:Column ColumnID="Name" dataindex="Name" Header="Field" Width="210" >
<Editor>
<ext:TextField ID="TextField00" runat="server" />
</Editor>
</ext:Column>
and outside of the column :
<DirectEvents>
<AfterEdit OnEvent="UpdateFieldValue"></AfterEdit>
</DirectEvents>
thanks
It works in this example.
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
Store store = this.GridPanel1.GetStore();
store.DataSource = new object[]
{
new object[] { "test1" },
new object[] { "test2" },
new object[] { "test3" }
};
store.DataBind();
}
}
protected void GridPanel_AfterEdit(object sender, DirectEventArgs e)
{
X.Msg.Alert("GridPanel_AfterEdit", "Hello from Server!").Show();
}
</script>
<!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>Ext.NET Example</title>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
<ext:GridPanel ID="GridPanel1" runat="server" AutoHeight="true">
<Store>
<ext:Store runat="server">
<Reader>
<ext:ArrayReader>
<Fields>
<ext:RecordField Name="test" />
</Fields>
</ext:ArrayReader>
</Reader>
</ext:Store>
</Store>
<ColumnModel runat="server">
<Columns>
<ext:Column Header="Test" DataIndex="test">
<Editor>
<ext:TextField runat="server" />
</Editor>
</ext:Column>
</Columns>
</ColumnModel>
<DirectEvents>
<AfterEdit OnEvent="GridPanel_AfterEdit" />
</DirectEvents>
</ext:GridPanel>
</form>
</body>
</html>
Hope this helps.

Why The error message for custom validator is not shown in message box?

I have tried in many way but the error message for custom validator is not shown in validation summary but it(ValidationSummary) shows error message for every other type of validator.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Expt_Custom Validator.aspx.cs" Inherits="Expt_Custom_Validator" %>
<!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>Untitled Page</title>
<script runat="server">
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
if (args.Value.Equals("Jagdeep"))
args.IsValid = false;
else
args.IsValid = true;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblName" runat="server" Text="Enter Your Name"></asp:Label>
<asp:TextBox ID="txtbxName" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="You are Not allowed" Display="None"
onservervalidate="CustomValidator1_ServerValidate"></asp:CustomValidator>
<br />
<asp:Label ID="lblClass" runat="server" Text="Class"></asp:Label>
<asp:TextBox ID="txtClass" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Please enter Clas" ControlToValidate="txtClass" Display="None"></asp:RequiredFieldValidator>
<br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Validate" />
</div>
</form>
</body>
</html>
Custom Validator, when placing in formview will not show its error message after server-side validation (though it has been validated and result is invalid) the mean to fix this in to wrap it by a Update Panel.
I solved this issue by registering a client script block, which updates the validation summary content. I have used jQuery for this:
private void DisplayCustomValidationMessage(CustomValidator cv, ValidationSummary vs)
{
if ((cv == null) || (vs == null)) return;
Type csType = this.GetType();
if (ClientScript.IsClientScriptBlockRegistered(csType, cv.ID)) return;
StringBuilder sb = new StringBuilder(#"<script type='text/javascript'>");
sb.Append(#"$(function () {");
sb.Append(#"var $vs = $('#" + vs.ClientID + "');");
sb.Append(#"if($vs.find('ul').length){");
sb.Append(#"$vs.find('ul').append('<li>" + cv.ErrorMessage + "</li>');");
sb.Append(#"}else{");
sb.Append(#"$vs.html('Fehlerhafte Eingabe(n):<ul><li>" + cv.ErrorMessage + "</li></ul>'); }");
sb.Append(#"$vs.css('display', 'block');");
sb.Append(#"});");
sb.Append(#"</script>");
ClientScript.RegisterClientScriptBlock(csType, cv.ID, sb.ToString());
}
The method has to be called if validation fails:
protected void cvYourCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = YourCustomValidationMethod();
if (!args.IsValid)
{
DisplayCustomValidationMessage((CustomValidator) source, vsYourValidationSummaryControl);
}
}

Resources