DataItem null reference

178 views Asked by At

I have a DataList and I am binding it in page load when it IS NOT a postback, but still I receive a null reference exception when I try to access the DataItem in the ItemCreated event, any suggestion?

protected void Page_Load(object sender, EventArgs e)
{
    AppPath = MapPath(HttpContext.Current.Request.ApplicationPath);
    MainDS.ReadXml(AppPath + FileName);
    DataView MyDV = new DataView(MainDS.Tables[0]);
    DataList1.DataSource = MyDV;
    DataList1.DataBind();           
}

protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{                  
    Response.Write(e.Item.DataItem.ToString());      
}
1

There are 1 answers

0
Shadow Wizard Love Zelda On

You need to check the item is ordinary item, not header or footer:

protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{                  
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        Response.Write(e.Item.DataItem.ToString());      
    }
}