Not failing if I cannot find a column in my dataset [CS/C# 2003]

Shaitan00

Junior Contributor
Joined
Aug 11, 2003
Messages
358
Location
Hell
Currently I use the following code to retrieve information from an XML file ... it works perfectly fine as long as the [type] (column name) exists in the DataRowView resulting from my .ReadXML.

Code:
DataSet dsxmlfile = new DataSet();
string sLabel = "";

dsxmlfile.ReadXml(filename);
if (dsxmlfile.Tables["Component"] != null ) 
{
	DataView dsview = dsxmlfile.Tables["Component"].DefaultView;

	// Check to see if the TYPE exists before trying to access it
	// ?????? //
					
	foreach (DataRowView a in dsview)
	{			
		sLabel = a[type].ToString();	// THIS IS WHERE THE EXCEPTION OCCURS where [type]="FirstV"
	}
		
	dsxmlfile.Dispose();
	return sLabel;
}				
dsxmlfile.Dispose();

The problem is - if I am looking for a [type] that does NOT exist I get the following exception:
Exception: FirstV is neither a DataColumn nor a DataRelation for table ComponentVersion.
Exception: at System.Data.DataRowView.get_Item(String property)

Therefore, I need a way to CHECK first if the COLUMN [type] exists and if not RETURN NULL and not cause an exception...
Is there a way to do this? Maybe using the XML toolset instead of Dataset/DataRowViews?

Any help, hints, or ideas would be greatly appreciated.
Thanks,
 
You should check the DataTable columns to see if it exists. You can go through your dsview variable to access the table and then the column collection to check.
Code:
            if (dsview.Table.Columns.Contains(type))
            {
                // do stuff
            }
 
Back
Top