简体   繁体   中英

Asp.net object reference error

In asp.net web application I get this error when populating datalist from database.
In design page I have some labels inside an item-template tag, when I try to access these labels by FindControl it gives the error:

Object reference not set to an instance of object

here is my code:

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>

Error:

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

Please help, how to get rid of this error ?

The list usually contains more than one item, so your logic is flawed. What you can do it handle the ItemDataBound event of the list by adding such line in your Page_Load :

DataList1.ItemDataBound += new DataListItemEventHandler(DataList1_ItemDataBound);

And have such method:

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

To customize your individual DataList items, you need to do it in the ItemDataBound event. Check out this tutorial for more details.

However, it looks like you are approaching your task in an incorrect manner. Bottom line is that you need to bind your DataSource to a collection of items, and you are trying to feed it items one-by-one. Let me know if I misunderstood you and you do need to bind an individual Product to your DataList customizing its appearance at bind time.

I think your lable put in other object same as panel. you should find the real name of your lable in html code, so the best way is putting a mistake error in you script code as a result when your solution is runnig it will stop and you can find the real name of your lable control. Then use below code :

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

I hope it can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM