Visual Studio.NET开发环境中常常用到DataList控件,尤其是常常在其中插入一个Label控件,用其绑定值,如下面的代码:注意id为“Label2”的Label控件,他就是为了绑定而插入的Label控件,而我这里主要想说明的是如何在程序中获得控件Label2的值。
DataList控件都有一些事件,获得Label2的值也应该在事件中,我就以ItemCommand事件为例,
如果我们在测试的时候发现我们并没有获得DataList中Label控件的值,这个时候我们要看看DataList中用来绑定的Label控件的书写格式如果是和下图一样则肯定不行
1
<
ItemTemplate
>
2 < TABLE >
3 < TR >
4 < TD width = " 150 " height = " 28 " >
5 < asp:Label id = " Label2 " runat = " server " Text = ' <%#Container.DataItem%> ' />
6
7 </ TD >
8 < TD width = " 40 " >
9 < asp:Button id = " selectbutton " runat = " server " ForeColor = " Blue " Text = " select " CommandName = " Select " ></ asp:Button ></ TD >
10 </ TR >
11 </ TABLE >
12 </ ItemTemplate >
2 < TABLE >
3 < TR >
4 < TD width = " 150 " height = " 28 " >
5 < asp:Label id = " Label2 " runat = " server " Text = ' <%#Container.DataItem%> ' />
6
7 </ TD >
8 < TD width = " 40 " >
9 < asp:Button id = " selectbutton " runat = " server " ForeColor = " Blue " Text = " select " CommandName = " Select " ></ asp:Button ></ TD >
10 </ TR >
11 </ TABLE >
12 </ ItemTemplate >
DataList控件都有一些事件,获得Label2的值也应该在事件中,我就以ItemCommand事件为例,
1
private
void
mylist_itemcommand(
object
source, System.Web.UI.WebControls.DataListCommandEventArgs e)
2 {
3 /**//*
4 注意FindControl这个系统自带的函数,(Label)是用来强制类型转换的,标准的写法如下
5 (System.Web.UI.WebControls.Label)e.Item.FindControl("所要查找Label控件的id")
6 */
7 System.Web.UI.WebControls.Label l = (Label)e.Item.FindControl("Label2");
8 string s = "你选择的是<b><font color=red>" + l.Text + "</font></b>";
9 this.Label1.Text=s;//Label1控件是用来测试获得的值
10 }
2 {
3 /**//*
4 注意FindControl这个系统自带的函数,(Label)是用来强制类型转换的,标准的写法如下
5 (System.Web.UI.WebControls.Label)e.Item.FindControl("所要查找Label控件的id")
6 */
7 System.Web.UI.WebControls.Label l = (Label)e.Item.FindControl("Label2");
8 string s = "你选择的是<b><font color=red>" + l.Text + "</font></b>";
9 this.Label1.Text=s;//Label1控件是用来测试获得的值
10 }
如果我们在测试的时候发现我们并没有获得DataList中Label控件的值,这个时候我们要看看DataList中用来绑定的Label控件的书写格式如果是和下图一样则肯定不行
1
<
asp:Label id
=
"
Label3
"
runat
=
"
server
"
><%
#Container.DataItem
%></
Label
>
但是如果书写格式如下图则可以,具体原因我也不知道,我是试出来的,希望对有些人有用。
1
<
asp:Label id
=
"
Label2
"
runat
=
"
server
"
Text
=
'
<%#Container.DataItem%>
'
/>