Reputation: 75
Below is my code and I am getting out of context error for workRow
variable, please resolve this issue I tried everything like written separate function to add row . . that is not helping me . . only (reader.Name == "Result")
I want to create roe and in other if want to add columns in that same row
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "Result")
{
DataRow workRow = dt.NewRow();
}
if (columns.Contains(reader.Name))
{
//ERROR IS HERE out of context
workRow[reader.Name] = reader.Value;
}
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
Upvotes: 2
Views: 130
Reputation: 7606
Please declare workRow outside if or add your workRow[reader.Name]
inside first if as shown below. The problem is you are scoping your workRow variable within the if (reader.Name == "Result")
, so when you try to access workRow outside this if block you will get error. Please check sample modification that may work for you
if (reader.Name == "Result")
{
DataRow workRow = dt.NewRow();
//Just a suggestion
if (columns.Contains(reader.Name))
{
workRow[reader.Name] = reader.Value;
}
}
Upvotes: 2
Reputation: 2678
Youre workRow variable is declared inside another if statement that's why you're getting that error.
DataRow workRow; // Moved the declaration here
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "Result")
{
workRow = dt.NewRow(); // this is okay if Result always comes first
}
if (columns.Contains(reader.Name))
{
//ERROR IS HERE out of context
workRow[reader.Name] = reader.Value;
}
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
Upvotes: 3
Reputation: 1861
Declare workflow to inner of correct if statement like below.
if (reader.Name == "Result")
{
//DataRow workRow = dt.NewRow();
}
if (columns.Contains(reader.Name))
{
DataRow workRow = dt.NewRow();
//ERROR IS HERE out of context
workRow[reader.Name] = reader.Value;
}
Upvotes: 1