回传时为什么Repeater控件中Literal控件无值(有示例)

Dic4000 Dic4000 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面是代码,可以直接Copy到工程中运行:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Menu.aspx.cs" Inherits="Menu"%>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">

<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<asp:LinkButton ID="btnAdd" runat="server" Text="增加" OnClick="btnAdd_Click"/>

<asp:Repeater ID="rept" runat="server" OnItemCreated="rept_ItemCreated" OnItemDataBound="rept_ItemDataBound" OnItemCommand="rept_ItemCommand">

<ItemTemplate>
<asp:Literal ID="Content" runat="server"/>
<asp:TextBox ID="tbx" runat="server"/>
<asp:LinkButton ID="btnUpdate" runat="server" Text="测试" CommandName="Update"/>
</ItemTemplate>
</asp:Repeater>

</form>
</body>
</html>



using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Collections;

public partial class Menu : System.Web.UI.Page
{

private string _cmd = DataControlCommands.SelectCommandName;



protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ArrayList ls = new ArrayList();

rept.DataSource = ls;
rept.DataBind();

}
}

protected void rept_ItemCreated(object sender, RepeaterItemEventArgs e)
{

if (e.Item.ItemType == ListItemType.Header) {}
else if (e.Item.ItemType == ListItemType.Footer) {}
else
{
if (_cmd == DataControlCommands.NewCommandName)
{
Literal content = e.Item.FindControl("Content") as Literal;
content.Text = "It is a Literal";//content.Text的内容是动态的,且只能在点新增按钮时赋给content.Text,不能在其它地方给content.Text赋值.这里为了测试方便写了个固定值
TextBox tbx = e.Item.FindControl("tbx") as TextBox;
tbx.Text = "It is a TextBox";

}
}
}

protected void rept_ItemCommand(object source, RepeaterCommandEventArgs e)
{


if (e.CommandName == DataControlCommands.UpdateCommandName)
{
Literal content = e.Item.FindControl("Content") as Literal;
TextBox tbx = e.Item.FindControl("tbx") as TextBox;
//为什么tbx.Text有值,而content.Text无值?
}
}

protected void rept_ItemDataBound(object sender, RepeaterItemEventArgs e)
{

}

protected void btnAdd_Click(object sender, EventArgs e)
{
ArrayList ls = new ArrayList();
ls.Add("1");
_cmd = DataControlCommands.NewCommandName;
rept.DataSource = ls;
rept.DataBind();

}
}



1:在rept_ItemCommand方法中添加断点
2:运行程序,首先点增加按钮,然后点测试按钮,点测试按钮后,程序会进入rept_ItemCommand方法,这时会发现tbx.Text有值,而content.Text无值.
问题:为什么这时候content.Text会没有值?想让它保有以前的值该怎么做?
...全文

相关推荐

评论 11
收藏 已收藏
分享
返回顶部
Dic4000
.NET社区 62,274 成员 668,968 内容