Skip to main content
 首页 » 编程设计

c#之无法从 GridView 中的 TemplateField 获取文本

2024年02月06日14luoye11

我有这个 GridView :

<asp:GridView runat="server" ID="gv_tList" OnRowDataBound="gv_tList_RowDataBound"> 
        <Columns> 
            <asp:BoundField DataField="taskID" HeaderText="taskID" />       
            <asp:TemplateField HeaderText="Description" > 
                <ItemTemplate> 
                    <asp:Label ID="descr" runat="server" Text='<%# Eval("Description") %>' ToolTip='<%# Eval("descr") %>' /> 
                </ItemTemplate> 
            </asp:TemplateField> 
        </Columns> 
</asp:GridView> 

和这段代码:

   protected void gv_tList_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
            string taskID = e.Row.Cells[0].Text; 
            e.Row.Cells[1].Text = e.Row.Cells[1].Text.Length > 40 ? e.Row.Cells[1].Text.Substring(0, 40) + ".." : e.Row.Cells[1].Text; 
        } 
    } 

e.Row.Cells[0].Text 返回文本字符串,但 e.Row.Cells[1].Text 返回“”。有人知道如何从单元格中获取文本吗?

请您参考如下方法:

您在 TemplateField 中声明标签,这样您就可以尝试这样的操作

   protected void gv_tList_RowDataBound(object sender, GridViewRowEventArgs e) 
    { 
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
           Label descr=(Label)e.Row.FindControl("descr"); 
           string Mydescr=descr.Text 
           string taskID = e.Row.Cells[0].Text; 
           descr.Text = descr.Text.Length > 40 ?  
           descr.Text.Substring(0, 40) + ".." : descr.Text; 
        } 
    }