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

时间:2011-06-06 02:37:30

标签: c# asp.net

我正在尝试将一个值从DetailsView传递给FormView,但我总是收到错误:对象引用未设置为对象的实例。不知怎的,它传递了一个值,我仍然可以执行插入。这是我第一次用C#编程。任何肝脏都会非常感激!

提前致谢

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

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();
            }
        }
    }
}

3 个答案:

答案 0 :(得分:2)

有几个地方可以检查是否为空。

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

您的代码的哪一行是抛出的异常?

答案 1 :(得分:2)

由于是软弹,所以在某些时候它无法施放。也许尝试使用显式转换或单步执行代码以查明FindControl是否返回控件。

答案 2 :(得分:0)

线程是旧的,但是当我在formview的itemtemplate和edititemtemplete中绑定下拉列表选择的值时,我遇到了这个错误。我通过将代码放在try catch语句中来解决这个问题。

相关问题