The Self-Taught Programmer

Recipes from real-world experience with asp.net.

How To Get Values from a DataTable without Crashing if a Column Doesn’t Exist

leave a comment »

The Situation

You have uploaded data into a DataTable (perhaps from a CSV file – see How To Parse a CSV File Into a DataTable for Use In Your Code) and now you need to retreive the data from the DataTable.

BUT because the data has come from an uploaded from a CSV file, it is possible that one or more of the required columns could be missing. How do you handle this problem without causing exceptions to be thrown?

The best solution in many cases would be to test the uploaded data to make sure all the columns are there, and if they aren’t, to notify the user to correct the file and reupload.

But what if you want to process the file even if a column is missing?

A Solution

In this situation, a good thing to do would be to process the data, but also notify the user that columns were missing. I do this by creating a private variable in the class:

private List<string> _missingcolumns;

Then create this function:

private static string GetColumnValue(DataRow row, string column)
{
	string result = "";
	if (row.Table.Columns.Contains(column))
	{
		if (CommonBase.HasValue(row[column].ToString()))
		{
			result = row[column].ToString();
		}
	}
	else
	{
		// Add to the list of missing columns if it isn't already in there
		if ( _missingcolumns.FindIndex(s => s == column) == -1 )
		{
			_missingcolumns.Add(column);
		}
	}

	return result;
}

Note that this function calls my common function library method ‘HasValue’, which can be found here.

Then call the function like this:

foreach ( DataRow r in dtable.Rows )
{
	string somevar = GetColumnValue(r, "Company Name");
}

(The variable ‘dtable’ is of type DataTable.)

So if the column exists and it has a value, you get the value (as a string). If the column exists but is null, you get back an empty string. If the column doesn’t exist, you get back an empty string. (You can of course alter this to suit your needs.)

Notify the User

If the column doesn’t exist, the name of the column is added to the _missingcolumns list, which you can use to notify the user that their data was processed but was incomplete.

Advertisements

Written by Jim McMullen

October 10, 2011 at 3:25 pm

Posted in How-To

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: