I made a custom user control and am having trouble setting a custom property. This is the code I'm having trouble with, I'm not sure why I'm getting the stack overflow exception. Any help would be much appreciated.
displayList = new List<ItemDisplay>();
foreach (var item in InventoryData2.Items)
{
ItemDisplay id = new ItemDisplay();
id.Item = item;
id.Name = item.Item.ItemNumber;
id.Location = new System.Drawing.Point(0, displayList.Count * id.Height);
displayList.Add(id);
}
public InventoryItem Item
{
get { return Item; }
set {
Item = value;
lblItemNumber.Text = Item.Item.ItemNumber;
lblTitle.Text = Item.Item.Title;
lblModel.Text = Item.Item.Model;
lblPrice.Text = Item.Item.Price.ToString();
}
}
The getter of this property will cause infinite recursion:
public InventoryItem Item { get { return Item; }
So will the setter:
set
{
Item = value;
You probably want something like this:
private InventoryItem item;
public InventoryItem Item
{
get
{
return this.item;
}
set
{
this.item = value;
lblItemNumber.Text = value.Item.ItemNumber;
lblTitle.Text = value.Item.Title;
lblModel.Text = value.Item.Model;
lblPrice.Text = value.Item.Price.ToString();
}
}
You have a "recursive" property access:
public InventoryItem Item
{
get
{
return Item; // <-- "recursive" getter
}
set
{
Item = value; // <-- "recursive" setter
lblItemNumber.Text = Item.Item.ItemNumber;
lblTitle.Text = Item.Item.Title;
lblModel.Text = Item.Item.Model;
lblPrice.Text = Item.Item.Price.ToString();
}
}
This should look like this (with a backing field):
private InventoryItem item;
public InventoryItem Item
{
get
{
return item;
}
set
{
item = value;
lblItemNumber.Text = item.Item.ItemNumber;
lblTitle.Text = item.Item.Title;
lblModel.Text = item.Item.Model;
lblPrice.Text = item.Item.Price.ToString();
}
}
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.