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

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();
		// Add to the list of missing columns if it isn't already in there
		if ( _missingcolumns.FindIndex(s => s == column) == -1 )

	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.

Leave a Reply

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

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

Facebook photo

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

Connecting to %s