我得到一个“对象引用未设置为对象的实例”。“welcome.Text = ....”行出现错误
家:
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>
我从 MCTS Exam 70-515 Web Dev book 中获得了代码。
我看了勘误表页面,没有运气。 http://oreilly.com/catalog/errataunconfirmed.csp?isbn=9780735627406
母版页:
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>
问候LF