Reputation: 4826
I'm not sure why this exception is happening... I could understand if I wasn't checking for i < table.Rows.Count
but I do check for this, so I am confused as to why the row is not in the table... I've hit a roadblock here and could use someone a little more experienced with this problem than me. I just hope it's one of those small stupid mistakes.
Edit: Earlier on I had a debug line myTable.Rows[0]["FieldName"]
and myTable.Rows[1]["FieldName"]
. The second one threw the exception as well, the first did not.
internal Collection<fieldDef> DefaultList
{
get
{
Collection<fieldDef> listFields = new Collection<fieldDef>();
listFields.Clear();
//Rows.Count is checked here, which is why I'm so confused...
for (int i = 0; i < myTable.Rows.Count; i++)
{
string strFieldName = "";
if (myTable.Rows[i]["FieldName"].ToString() != "") //Exception happens here
{
strFieldName = myTable.Rows[i]["FieldName"].ToString();
}
FieldType type = FieldType.Character;
if (myTable.Rows[i]["FieldType"].ToString() != "") type = (FieldType)Enum.Parse(typeof(FieldType), myTable.Rows[i]["FieldType"].ToString());
//
//Other Similar lines to that above
//
fieldDef def = new fieldDef(i, strFieldName, strFieldName, type, /*other items...*/);
listFields.Add(def);
}
return listFields;
}
set
{
//Nothing negative happens here, left out for simplicity
}
}
Upvotes: 3
Views: 3426
Reputation: 4826
I found the solution. Just posting in case anyone has the same problem. It's not stated in the original post, but this is called via change/edit events on the DataTable (which are triggered by button clicks and required to save settings).
The issue is that if you try to get the property within the event, the row is actually pulled from the table (like when it is being moved up or down) and the state is "detached", therefore, no longer officially in the table.
To solve this, I simply waited to access my property until after the event had completely finished (thus the row being fully placed back into the table) which required a little reworking of other parts of my code.
Hope this helps someone down the road!
Upvotes: 3
Reputation: 536
I don't have the 50 rep yet to be able to comment/ask questions, so my answer is based on what I am seeing above...
To start, it would be helpful if you included what your error/exception is. That said, while you may have a row, you are not checking for null when calling the FieldName field in that row--are you sure you have a non-null value in that field, in that row? If it is null, calling .ToString() will throw an exception...I would suggest something like this:
if (myTable.Rows[i]["FieldName"] != null && myTable.Rows[i]["FieldName"].ToString() != "") //Exception happens here
{
strFieldName = myTable.Rows[i]["FieldName"].ToString();
}
This may or may not be your issue, but either way, checking for null here would be good practice and help avoid invalid operations such as trying to a null instance.
Upvotes: 0