1

I have a DataTable with 3 columns: URL [string], Date [DateTime], DestinationFile [string]

Using a method, I connect to the internet and fill the first two columns (URL, Date) with a list of URLs and the date they were uploaded

Using another method, I need to fill the third column (DestinationFile) with a string array including a specific path for each file. The string array has the same size as the number of rows of the DataTable.

Is it possible to fill the third column of the DataTable with an array of strings (in this case, but it could be of any type)?

Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
argledhel
  • 167
  • 2
  • 3
  • 16

1 Answers1

3

There is no way to do it directly in one step, so you will have to change values manually in a loop using Rows collection of the datatable and indexer property of the DataRow:

DataTable dt = ...
String[] destinationFiles = ...
Int32 destinationFileColumnIndex = 2;

if (dt.Rows.Count != destinationFiles.Length)
   throw new Exception("Lengthes are inconsistent");

for (int i = 0; i < destinationFiles.Length; i++)
{
    dt.Rows[i][destinationFileColumnIndex] = destinationFiles[i];
}

If destinationFiles have type that is different from String, then either DataTable column should be changed to have appropriate type, or you have to convert values of that type to string.

To achieve it you should either call .ToString() method, if it is correctly implemented:

SomeType[] destinationFiles = ...
// ...
    dt.Rows[i][destinationFileColumnIndex] = destinationFiles[i].ToString();

or manually form the string to set:

SomeType cur = destinationFiles[i];
dt.Rows[i][destinationFileColumnIndex] = String.Format("{0} and {1}",
     cur.Prop1,
     cur.Prop2);

EDIT:

Direct method is so unfortunately absent, but there is such thing as Extension Methods:

public static class DataColumnExtensions
{
    // Will work with both the arrays and lists
    public static void SetValues<T>(this DataColumn column, IList<T> values)
    {
        if (column == null)
            throw new ArgumentNullException("column");
        if (values== null)
            throw new ArgumentNullException("values");

        DataTable dt = column.Table;             

        if (dt.Rows.Count != values.Count)
             throw new Exception("Lengths are inconsistent");

        for (int i = 0; i < values.Count; i++)
        {
            dt.Rows[i][column] = values[i];
        }
    }
}

and use it like:

dt.Columns[2].SetValues(new String[] {....});

Just put it into the same namespace as your code, or as a better practice put it into some appropriately named namespace and make using AppropriatelyNamedNamespace; only when you need it.

Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53