在ListView EmptyDataTemplate中查找控件
我有一个像这样的ListView
...
在Page_Load()
我有以下内容:
Literal x = (Literal)ListView1.FindControl("Literal1"); x.Text = "other text";
但是x
返回null
。 我想更改Literal
控件的文本,但我不知道该怎么做。
我相信除非你在代码后面的某个地方调用ListView
的DataBind
方法,否则ListView
永远不会尝试数据绑定。 然后什么都不会渲染,甚至不会创建Literal
控件。
在您的Page_Load
事件中尝试类似于:
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { //ListView1.DataSource = ... ListView1.DataBind(); //if you know its empty empty data template is the first parent control // aka Controls[0] Control c = ListView1.Controls[0].FindControl("Literal1"); if (c != null) { //this will atleast tell you if the control exists or not } } }
您可以使用以下内容:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.EmptyItem) { Control c = e.Item.FindControl("Literal1"); if (c != null) { //this will atleast tell you if the control exists or not } } }
这不是你提出的具体问题,但另一种做这种事情的方法是这样的:
<%= Foobar() %>
Foobar在页面的代码隐藏文件中定义
public partial class MyClass : System.Web.UI.Page { ... public string Foobar() { return "whatever"; } }
另一种方法……
...
代码隐藏……
protected void Literal1_Init(object sender, EventArgs e) { (sender as Literal).Text = "Some other text"; }
Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound Dim searchValue As String = Replace(Request.QueryString("s"), "", "'") Dim searchLiteral2 As Literal = CType(ListView1.FindControl("Literal2"), Literal) searchLiteral2.Text = "''" & searchValue & "''" End Sub
…
回答Broam的问题“在数据绑定方法中有没有办法做到这一点?我宁愿不硬编码”控件[0]“,因为那是”马虎“
protected void ListView1_DataBound(object sender, EventArgs e) { ListView mylist = ((ListView)sender); ListViewItem lvi = null; if (mylist.Controls.Count == 1) lvi = mylist.Controls[0] as ListViewItem; if (lvi == null || lvi.ItemType != ListViewItemType.EmptyItem) return; Literal literal1 = (Literal)lvi.FindControl("Literal1"); if (literal1 != null) literal1.Text = "No items to display"; }
不幸的是,我没有找到一种不使用Controls [0]的方法。
在通常的Item事件(ItemDataBound或ItemCreate)中,您可以使用ListViewItemEventArgs的e.Item来获取ListViewItem。 在DataBound事件中,只有一个通用的EventArgs。
最重要的是,似乎((控制)发送者).FindControl(“Literal1”)也不起作用(从树顶部的列表视图中找到控制),因此使用Controls [0]。 FindControl(…)(从listviewitem中找到控件)。