【问题标题】:Asp.net object reference errorAsp.net 对象引用错误
【发布时间】:2013-10-13 11:33:45
【问题描述】:

在 asp.net Web 应用程序中,从数据库中填充 datalist 时出现此错误。
在设计页面中,我在项目模板标签中有一些标签,当我尝试通过 FindControl 访问这些标签时,它会给出错误:

对象引用未设置为对象实例

这是我的代码:

Products.aspx.cs:

    public partial class Products : System.Web.UI.Page
    {                    
        Product product;             

        protected void Page_Load(object sender, EventArgs e)
        {    
            if (!IsPostBack)
                DataList1.DataBind();
            product = this.getProducts();

            Label TitleLabel = (Label)DataList1.FindControl("TitleLabel");
            TitleLabel.Text = product.Name;    

            Label DescLabel = (Label)DataList1.FindControl("DescLabel");
            DescLabel.Text = product.LongDescription;    

            Label PriceLabel = (Label)DataList1.FindControl("PriceLabel");
            PriceLabel.Text = product.UnitPrice.ToString();    

            ImageButton PImage = (ImageButton)DataList1.FindControl("ImageButton1");
            PImage.ImageUrl = "images/"+product.ImageFile;                     
        }    

        private Product getProducts()
        {
            Product p = new Product();

            DataView productsTable = (DataView)
            SqlDataSource1.Select(DataSourceSelectArguments.Empty);

            foreach (DataRowView row in productsTable)
            {    
                p.ProductID = row["P_Id"].ToString();
                p.Name = row["Title"].ToString();
                p.ShortDescription = row["Desc"].ToString();
                p.LongDescription = row["Desc_full"].ToString();
                p.UnitPrice = Convert.ToDecimal(row["Price"]);
                p.ImageFile = row["imageurl"].ToString();                                
            }                      
            return p;    
        }
    }

Products.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Products.aspx.cs" Inherits="ECProject.Products" %>

<!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:DataList ID="DataList1" runat="server" DataKeyField="P_Id" 
            DataSourceID="SqlDataSource1" RepeatColumns="4" 
            RepeatDirection="Horizontal" CellPadding="4" ForeColor="#333333"  >
            <AlternatingItemStyle BackColor="White" ForeColor="#284775"  />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <ItemTemplate >

                <asp:ImageButton ID="ImageButton1" runat="server"  Height = "200px"/>
                <br />

                Title:
                <asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
                <br />                   

                Brand:
                <asp:Label ID="DescLabel" runat="server" Text='<%# Eval("Desc") %>'  />
                <br />                                      

                Available:
                <asp:Label ID="Is_ActiveLabel" runat="server" Text='<%# Eval("Is_Active") %>' />
                <br />    

                 Price:
                <asp:Label ID="PriceLabel" runat="server" Text='<%# Eval("Price") %>' />
                   <br />
            </ItemTemplate>
            <SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        </asp:DataList>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ECDB.mdf;Integrated Security=True;User Instance=True" 
            ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [Product]">
        </asp:SqlDataSource>        
    </div>
    </form>
</body>
</html>

错误:

Line 25:             
Line 26:             Label TitleLabel = (Label)DataList1.FindControl("TitleLabel");
Line 27:             TitleLabel.Text = product.Name;
Line 28: 
Line 29: 

请帮忙,如何摆脱这个错误?

【问题讨论】:

标签: c# asp.net nullreferenceexception


【解决方案1】:

该列表通常包含多个项目,因此您的逻辑有缺陷。您可以通过在您的Page_Load 中添加这样的行来处理列表的ItemDataBound 事件:

DataList1.ItemDataBound += new DataListItemEventHandler(DataList1_ItemDataBound);

并且有这样的方法:

void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Label TitleLabel = (Label)e.Item.FindControl("TitleLabel");
        TitleLabel.Text = "changed by code";
    }
}

【讨论】:

    【解决方案2】:

    要自定义您的各个 DataList 项,您需要在 ItemDataBound 事件中进行。查看this 教程了解更多详情。

    但是,您似乎以不正确的方式处理任务。底线是您需要将 DataSource 绑定到项目集合,并且您正尝试将项目一个接一个地提供给它。如果我误解了您,请告诉我,您确实需要将单个 Product 绑定到 DataList 以在绑定时自定义其外观。

    【讨论】:

      【解决方案3】:

      我认为您的标签放在与面板相同的其他对象中。你应该在 html 代码中找到你的标签的真实名称,所以最好的方法是在你的脚本代码中添加一个错误错误,结果当你的解决方案运行时它会停止并且你可以找到你的标签控件的真实名称。然后使用下面的代码:

      Label TitleLabel = (Label)DataList1.FindControl("REAL NAME OF LABEL CONTROL");

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2011-02-08
        • 1970-01-01
        • 2011-02-25
        • 2012-02-03
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 2014-08-04
        • 1970-01-01
        相关资源
        最近更新 更多