我正在尝试将数据添加到位于 GridView 内的文字中。当前代码如下所示
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = "<h3>" + list.title + "</h3>";
info.Text += "<h4>" + list.description + "</h4>";
}
}
}
这将产生一个错误
Object reference not set to an instance of an object.
如果有人对此有任何想法,那将会有很大帮助
谢谢
最佳答案
确保您只操作数据行,而不是页眉、页脚、分隔符、分页器等。其枚举为 DataControlRowtype
。这就是为什么您的 info
对象/引用为 null,因为它首先对 header 进行操作。
- 检查
e.Row.RowType
的类型是否为DataRow
。 - 为了安全起见,还要检查您的
info
是否不为空。
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null && info !=null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = string.Format("<h3>{0}</h3><h4>{1}</h4>",
list.title, list.description);
}
}
}
}
关于c# - 将数据动态添加到 GridView 内的 asp 文字控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7309885/