设置 - 我希望用户输入塑料卡的详细信息。他们可以点击AddNewCard按钮添加多张卡片。
代码
[Serializable]
public class Card
{
public string Number { get; set; }
public string Code { get; set; }
}
public class CardControl : CompositeControl
{
private LinkButton _lnkAddNewCard = new LinkButton { Text = "Add Card" };
private PlaceHolder _plcListCards=new PlaceHolder();
private IList<Card> _lstCards
{
get { return (IList<Card>) ViewState["ListCards"]; }
set { ViewState["ListCards"] = value; }
}
protected override void OnInit(EventArgs e)
{
_lnkAddNewCard.Click+=_lnkAddNewCard_Click;
}
void _lnkAddNewCard_Click(object sender, EventArgs e)
{
var lstCards = _lstCards ?? new List<Card>();
lstCards.Add(new Card());
_lstCards = lstCards;
RenderCard(_lstCards[lstCards.Count - 1]);
}
protected override void CreateChildControls()
{
Controls.Clear();
Controls.Add(_lnkAddNewCard);
Controls.Add(_plcListCards);
RenderCards();
}
protected void RenderCards()
{
_plcListCards.Controls.Clear();
if(_lstCards == null) _lstCards = new List<Card> { new Card() };
foreach (var card in _lstCards)
RenderCard(card);
}
protected void RenderCard(Card card)
{
_plcListCards.Controls.Add(new TextBox() { Text = card.Number});
_plcListCards.Controls.Add(new TextBox() { Text = card.Code});
}
}
问题
答案 0 :(得分:0)
新卡尚未订阅所创建的点击事件。每次创建新卡时都需要添加事件处理程序。
var newCard = new Card();
newCard.Click+=_lnkAddNewCard_Click;
_lstCards.Add(new newCard);
答案 1 :(得分:0)
你必须致电
_lnkAddNewCard.Click+=_lnkAddNewCard_Click;
在每个帖子中 所以_lnkAddNewCard_Click将是
void _lnkAddNewCard_Click(object sender, EventArgs e)
{
_lnkAddNewCard.Click+=_lnkAddNewCard_Click;
var lstCards = _lstCards ?? new List<Card>();
lstCards.Add(new Card());
_lstCards = lstCards;
RenderCard(_lstCards[lstCards.Count - 1]);
}