简体   繁体   中英

object references not set to an instance of the object

Am running asp.net application with c#.Am using gridview to update and delete the columns.deleting is working fine.if am clicking the update button i got

System.NullReferenceException: Object reference not set to an instance of an object.

My code is;

    protected bool IsRowModified(GridViewRow row)
    {
        int currentID;
        string currentName;
        string currentLocation;
      currentID = Convert.ToInt32(GridView1.DataKeys
                                [row.RowIndex].Value);

        currentName = ((TextBox)row.FindControl
                                      ("txtName")).Text;
        currentLocation = ((TextBox)row.FindControl
                                  ("txtLocation")).Text;




        **System.Data.DataRow newRow = originalTable.Select
                (String.Format("ID = {0}", currentID))[0];** //got error in this line

        if (!currentName.Equals(newRow["Name"].ToString()))
        { return true; }
        if (!currentLocation.Equals(newRow["Location"].ToString()))
        { return true; }

        return false;

    }

Either originalTable is null, or originalTable.Select(...) is returning null.

Could it be that you've deleted the underlying data from originalTable and not updated the UI?

An alternative method might be to use the DataItem property of the GridViewRow parameter:

protected bool IsRowModified(GridViewRow row)     
{                     
    string currentName = ((TextBox)row.FindControl("txtName")).Text;
    string currentLocation = ((TextBox)row.FindControl("txtLocation")).Text;                            
    DataRow newRow = (DataRow)row.DataItem;

    if (!string.Equals(currentName, newRow["Name"].ToString()))         
    { 
        return true; 
    }         
    if (!string.Equals(currentLocation, newRow["Location"].ToString()))         
    { 
        return true; 
    }          

    return false;      
} 

My guess is that your currentID variable is null or empty. You should check your values for null or empty before you try to use them.

if(!String.IsNullOrEmpty(currentID))
{
   // Continue processing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM