I'm trying to loop through rows and get their Indexes (Primary Keys from SQL). I'm getting a NRE on "this.SelectRowIndexes.Add(ResourceKey)" I can't figure out why it would matter and how can I fix this?
CODE:
private void GetIndexes()
{
List<int> SelectRowIndexes = new List<int>();
for (int i = 0; i < gridViewRecords.Rows.Count; i++)
{
DataRowView drv = (DataRowView)gridViewRecords.CurrentRow.DataBoundItem;
DataRow selectedRow = drv.Row;
ResourceKey = Convert.ToInt32(selectedRow["ResourceAndInstallKey"]);
this.SelectRowIndexes.Add(ResourceKey);
}
}
I also have it up in my class (this has been a ton of troubleshooting, so my code looks terrible)
public List<int> SelectRowIndexes { get; set; }
I had this prior. Several of the answers quoted this code. I changed mine because the if-else was actually used for something else, which has now been deleted
if (this.SelectRowIndexes == null)
{
this.SelectRowIndexes.Add(ResourceKey);
}
else
{
this.SelectRowIndexes.Add(ResourceKey);
}
What do you actually want to do if this.SelectRowIndexes
is null? Currently you're just unconditionally calling Add
on it, because both branches of your if
statement do the same thing.
Note that it definitely wouldn't be null if you'd assigned a new value to it - but instead in this line, you're declaring a new local variable called SelectRowIndexes
:
List<int> SelectRowIndexes = new List<int>();
... which you're then completely ignoring. Perhaps you meant to set the value of the property/field instead?
SelectRowIndexes = new List<int>();
With that change, you should avoid the exception - but you'll still have the basically-broken code. You should almost certainly just get rid of the if
check... it's not doing you any good right now.
However, I would suggest that you probably should be declaring a separate local variable for resourceKey
- the fact that you're updating an instance variable in a loop is somewhat peculiar... as is the fact that you're not using your loop index at all... you're doing the same thing for each iteration of the loop, using the current row rather than row i
. Is that deliberate?
Fundamentally, you might well want to start this code again... it looks like you might just want to use LINQ:
private void GetIndexes()
{
SelectRowIndexes = gridViewRecords.Rows
.Cast<DataRowView>()
.Select(drv => (int) drv.Row["ResourceAndInstallKey"])
.ToList();
}
See more on this question at Stackoverflow