3
votes

below is the code i'm using and i've used this 100x's before. And now it's throwing an error, basically i'm trying to dynamically create the Columns based on the first row of an excel file. The error that i'm receiving now is:

The call is ambiguous between the following methods or properties: 'System.Data.DataColumnCollection.Add(System.Data.DataColumn)' and 'System.Data.DataColumnCollection.Add(string)'

DataTable excel_Holding_Table = new DataTable();
        DataRow row;
        Microsoft.Office.Interop.Excel.Range range = workSheet.UsedRange;
        for (int i = 1; i <= range.Columns.Count; i++)
        {
            excel_Holding_Table.Columns.Add(Convert.ToString(((Microsoft.Office.Interop.Excel.Range)workSheet.Cells[1, i]).Value2));
        }

What do I need to do to prevent this from happening, this has never appeared.

here is my using:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
1

1 Answers

4
votes

My guess is that Convert.ToString is returning null, but because you're calling Add dynamically, it can't work out the overload based on the actual type.

Fortunately, we can improve the code's readability and fix the problem at the same time:

for (int i = 1; i <= range.Columns.Count; i++)
{
     // Note: Add using directive for Microsoft.Office.Interop.Excel
     Range range = (Range) workSheet.Cells[1, i];
     string value = Convert.ToString(range.Value2);
     excel_Holding_Table.Columns.Add(value);
}