当我想编辑时,对象引用未设置为对象的实例?

时间:2013-12-05 12:19:50

标签: c#

我是初学者,当我点击gridview上名为“编辑”的链接按钮时出现问题,它会抛出一个错误,说“对象引用没有设置为对象的实例”

如果我下次收到相同的错误或任何有助于我必须注意的提示,你能不能请我参考一些网站以获得正确的理解。

请参阅下面的代码;

protected void grdDepartment_command(object sender, GridViewCommandEventArgs e)
{
    GridViewRow _Row = gridDepartment.SelectedRow;
    // it shows the error here.
    string str = _Row.Cells[0].Text; 
    ViewState["DepartmentID"] = str;

    IList<MCX.ISupplierPortal.Database.dptDEPARTMENT> _EditDepartment = _decDepartment.GetDepartment(int.Parse(str));

    if (_EditDepartment != null)
    {
        foreach (MCX.ISupplierPortal.Database.dptDEPARTMENT _DepartmentList in _EditDepartment)
        {
            txtDepartmentName.Text = _DepartmentList.DepartmentName;
            txtDescription.Text = _DepartmentList.DepartmentDesc;
            ViewState["DepartmentID"] = _DepartmentList.DepartmentID.ToString();
        }          
    }
    ViewState["PageMode"] = "Update";
}

此处发生异常

GridViewRow _Row = gridDepartment.SelectedRow;
// it shows the error here.  
string str = _Row.Cells[0].Text;
ViewState["DepartmentID"] = str;

2 个答案:

答案 0 :(得分:1)

if(_Row!=null)
{
    string str = _Row.Cells[0].Text; -->it shows the error her.
    ViewState["DepartmentID"] = str;

    IList<MCX.ISupplierPortal.Database.dptDEPARTMENT> _EditDepartment =_decDepartment.GetDepartment(int.Parse(str));

    if (_EditDepartment != null)
    {
        foreach (MCX.ISupplierPortal.Database.dptDEPARTMENT _DepartmentList in _EditDepartment)
        {
            txtDepartmentName.Text = _DepartmentList.DepartmentName;
            txtDescription.Text = _DepartmentList.DepartmentDesc;
            ViewState["DepartmentID"] = _DepartmentList.DepartmentID.ToString();

        }                   
    }
    ViewState["PageMode"] = "Update";
}

您应该检查所选行是否为空。如果不是,那么您可以执行您编写的代码。否则,所选行为空。因此,所选行不会指向托管堆中的对象。因此,您无法尝试读取不存在的对象的属性。

答案 1 :(得分:1)

GridViewRow row = gridDepartment.Rows[ Convert.ToInt32(e.CommandArgument)];
if(row != null)
{
       //do work
}