c# - asp.net标签文本元素与普通文本的区别

标签 c# asp.net gridview

我有疑问

下面这些类型的标签文本声明有什么不同?

 <asp:Label ID="lbl2" **Text="Name"** runat="server"></asp:Label>

 <asp:Label ID="lbl2"  runat="server"**>Name</**asp:Label>

我直接在文本属性中提供了文本 Text="Name"并在标签字段中心提供文本 > Name </

我的 gridview 控件上有更多标签,我想在编辑网格时获取标签文本值,我正在使用查找控件来获取标签值

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Label xx = GridView1.Rows[e.NewEditIndex].FindControl("lbl2") as Label;
        Label yy = GridView1.Rows[e.NewEditIndex].FindControl("lbl2") as Label;
        txtName.Text = xx.Text;
        txtAge.Text = yy.Text;
    }

这是我的 GridView 代码

 <asp:TemplateField HeaderText="Name">
                        <ItemTemplate>
                            <asp:Label ID="lbl1" Text='<%#  Eval("StudentName") %>' runat="server"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

它工作正常,如果我把 Eval 值放在标签的文本属性中,但是如果我在标签的中心提供 eval 值,比如 ( <asp:Label ID="lbl1" runat="server"><%# Eval("StudentName") %></asp:Label> ) 然后 find control 没有返回值,它返回空("") 。为什么?

编辑:

But if I set the label text in outside of gridview , both of way's are working good(lblid.text give correct if set the text in that two way ) ! only i got the problem in label inside of gridview !

最佳答案

what is the difference between this label text type ?

<asp:Label ID="lbl2" **Text="Name"** runat="server"></asp:Label>

将创建一个 Label 控件,其中 Text 属性的值为“Name”

<asp:Label ID="lbl2"  runat="server"**>Name</**asp:Label>

将创建一个Label控件

  • Text 属性的值为 String.Empty
  • 使用 Literal 子控件,Text 属性值为“Name”

请注意,同时使用这两种行为(设置 Text 属性和拥有内容)可能会导致意外行为:参见 http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.label.text.aspx

Note : Setting the Text property will clear any other controls contained in the Label control.

所以我认为问题是当你写的时候:

<asp:Label ID="lbl2"  runat="server"**><%#  Eval("StudentName") %></**asp:Label>

然后

Label xx = GridView1.Rows[e.NewEditIndex].FindControl("lbl2") as Label;
txtName.Text = xx.Text;

您正在尝试访问尚未被 DataBound 的子文字控件的值

不确定它是否有效或有所作为,但您可以尝试:

Label xx = GridView1.Rows[e.NewEditIndex].FindControl("lbl2") as Label;
xx.Controls[0].DataBind();
txtName.Text = xx.Text;

无论如何,到现在为止您应该已经想到您最好使用 Label 的 Text 属性而不是隐式的 Text Literal

关于c# - asp.net标签文本元素与普通文本的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19583702/

相关文章:

asp.net - 如何从 javascript 从 asp.net 文本框中检索值?

c# - 从 GridView 导出为 PDF

android - 我想将我的 GridView 保存在一个 ImageView 中

c# - Magento 从 C# 应用程序通过 SOAP 添加产品

c# - 必须在 C# 中声明标量变量

c# - 计数子记录,如果为空则显示零

c# - 输入的字符串格式不正确

c# - 如何自定义 TreeNode 在 TreeView 中的显示顺序/位置?

c# - 使用日期搜索时出错

c# - 错误 :Index (zero based) must be greater than or equal to zero and less than the size of the argument list