Object reference not set to an instance of an object

נעול Object reference not set to an instance of an object

  • Friday, September 14, 2012 6:51 PM
     
      Has Code
    I'm having trouble with updating a specific field of an ListView.

    I need to update SubItem 'Value' at Column 'Product.Text' and row 2.

    I tryed this code: 
    lvMain.Items[Product.Text].SubItems[1].Text = Value;  
    but its giving me this error:
    Object reference not set to an instance of an object.

    Is there another method to update a specific column and row of a ListView?

All Replies

  • Saturday, September 15, 2012 11:40 AM
     
     

    Usually the access to item is not with [Product.Text] (as it is a string), but with an index. Read this:

    http://www.c-sharpcorner.com/UploadFile/mgold/ListViewInCSharp11172005021741AM/ListViewInCSharp.aspx

    There is an example there: listView1.ListItems[i].SubItems[1].ToString());

    Anyway, Bing for "c# listview" for example that will show you some more tips.

    You mention that the error message is "obj reference not set". This is caused by using something that has not been declared. It could be that you don't have yet SubItem[1] as this is not available in code time, but only in run-time.

    You need to learn a bit more of debugging stuff in run-time, as setting breakpoints and inspect objects and variables, like setting a breakpoint there and "add watch" of your objects, like the lvMain and check for items there.

    Happy coding!


    Adelino Araujo

  • Saturday, September 15, 2012 12:49 PM
     
     

    Thanks for your reaction. It's simple to select a row by index. But I need to select a row if its equal to Product.Text which is a string.

  • Saturday, September 15, 2012 1:37 PM
     
     Answered
    Oh, you have an example here http://www.codeproject.com/Articles/19108/ListView-Find-Items-Text and use IndexOfKey.

    Adelino Araujo

    • Marked As Answer by ChrisjuhB Saturday, September 15, 2012 2:04 PM
    •  
  • Saturday, September 15, 2012 2:04 PM
     
     
    Thanks that's what I was looking for.