对象引用未设置为对象的实例

本文关键字:实例 对象 设置 对象引用 | 更新日期: 2023-09-27 17:58:30

我试图将一个值从DetailsView传递到FormView,但总是收到一个错误:对象引用没有设置为对象的实例。不知怎么的,它确实传递了一个值,我仍然可以执行插入。这是我第一次用C#编程。任何hep都将不胜感激!

提前感谢

我在这里附上了一个代码。我认为这里的问题是我没有空支票,所以我如何添加空支票?

using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
    public partial class BookLending : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void FormView1_DataBound(object sender, EventArgs e)
        {
            if(FormView1.CurrentMode == FormViewMode.Insert && FormView1.Fin != null) 
            {
                TextBox bookid = FormView1.FindControl("bookidTextBox") as TextBox;
                bookid.Text = ((DataRowView)DetailsView1.DataItem)["bookid"].ToString();
            }
            {
                TextBox employee = FormView1.FindControl("EmployeeIDTextBox") as TextBox;
                employee.Text = ((DataRowView)DetailsView1.DataItem)["EmployeeID"].ToString();
            }
        }
    }
}

对象引用未设置为对象的实例

有几个地方可以检查null。

1) 如果你的演员阵容不正确:

TextBox bookid = FormView1.FindControl("bookidTextBox") as TextBox;
if (bookid != null)
    bookid.Text = ((DataRowView)DetailsView1.DataItem)["bookid"].ToString();
TextBox employee = FormView1.FindControl("EmployeeIDTextBox") as TextBox;
if (employee != null)
    employee.Text = ((DataRowView)DetailsView1.DataItem)["EmployeeID"].ToString();

2) 如果控件没有值,ToString()还会抛出对象null引用异常:

((DataRowView)DetailsView1.DataItem)["bookid"] != null
((DataRowView)DetailsView1.DataItem)["EmployeeID"] != null

异常是在代码的哪一行引发的?

As是软强制转换,因此在某些情况下无法强制转换。也许可以尝试使用显式强制转换或逐步遍历代码来确定FindControl是否返回控件。

Thread是旧的,但我在绑定formview的itemtemplate和edititemtemplete中的dropdownlist选定值时遇到了这个错误。我通过将代码放入try-catch语句来解决这个问题。