设定数据在GridView的标签 [英] Set data to a label in GridView

查看:185
本文介绍了设定数据在GridView的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个asp GridView的一个标签,我想绑定数据集到它。
结果这里是我的RowDataBound方法:

 保护无效GridView1_RowDataBound(对象发件人,GridViewRowEventArgs E)
{
    变量名称=(标签)e.Row.FindControl(LABEL_NAME);
    name.Text =萨拉;
    name.DataBind();
}

和这里是我的GridView:

 < ASP:GridView控件ID =GridViewCertificateType=服务器的AutoGenerateColumns =FALSEOnRowDataBound =GridView1_RowDataBound>< ASP:标签ID =LABEL_NAME=服务器文本=>< / ASP:标签>

但经过 name.Text =萨拉; ,我收到此异常:

 对象引用未设置到对象的实例。


解决方案

在您的RowDataBound方法,确保你有一个条件检查该行的类型是什么。本次活动将在你的GridView调用的每一行,包括页眉和页脚行。如果标题行中没有找到 LABEL_NAME ,你就会有一个空的对象。一旦你这样做,摆脱 name.DataBind()的; ,因为它不需要

 保护无效GridView1_RowDataBound(对象发件人,GridViewRowEventArgs E)
{
    如果(e.Row.RowType == DataControlRowType.DataRow)
    {
        变量名称=(标签)e.Row.FindControl(LABEL_NAME);
        name.Text =萨拉;
    }
}

I have a label in an asp GridView and I want to set bind data to it.
Here is my RowDataBound method:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    var name = (Label)e.Row.FindControl("Label_name");
    name.Text ="sara";      
    name.DataBind();
}

and here is my GridView:

<asp:GridView ID="GridViewCertificateType" runat="server" AutoGenerateColumns="False"   OnRowDataBound="GridView1_RowDataBound" >

<asp:Label ID="Label_name" runat="server" Text="" ></asp:Label>

But after name.Text ="sara";, I receive this exception:

Object reference not set to an instance of an object. 

解决方案

In your RowDataBound method, make sure you have a condition to check what the type of the row is. This event will be called for every row in your GridView, including header and footer rows. If Label_name is not found in the header row, you'll have a null object. Once you do that, get rid of name.DataBind();, as it is not needed.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var name = (Label)e.Row.FindControl("Label_name");
        name.Text = "sara"; 
    }
}

这篇关于设定数据在GridView的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆