Amanda
Amanda

Reputation: 13

Specifying the columns of the datatable in a general method C#

I already have the code that specify columns of the dataTable but what I want is to create a general method that has in her parameters: ColumnName and types. How can I do that?

This is my code:

column = dt.Columns.Add();
column.ColumnName = "IPPName";
column.DataType = typeof(String);

column = dt.Columns.Add();
column.ColumnName = "tagName";
column.DataType = typeof(String);

column = dt.Columns.Add();
column.ColumnName = "time";
column.DataType = typeof(String);

column = dt.Columns.Add();
column.ColumnName = "value";
column.DataType = typeof(Double);

column = dt.Columns.Add();
column.ColumnName = "qtity";
column.DataType = typeof(Double);

Upvotes: 0

Views: 147

Answers (2)

flindeberg
flindeberg

Reputation: 5027

An additional way to solve it using extensionmethods. I believe it is a tad easier to follow than @adt answer and more useful since it can be called on an already existing DataTable.

If you need help regarding extensionmethods, have a look at this description or just ask :)

public static class DataTableExtentions {
  public static void AddColumn(this DataTable table, string columnName, Type columnType)
  {
    var col = table.Columns.Add();
    col.ColumnName = columnName;
    col.DataType = columnType;
  }
}

And it would be called like this:

column = dt.AddColumn("IPPName", typeof(String));

column = dt.AddColumn("tagName", typeof(String));

column = dt.AddColumn("time", typeof(String));

column = dt.AddColumn("value", typeof(Double));

column = dt.AddColumn("qtity", typeof(Double));

Upvotes: 0

adt
adt

Reputation: 4360

I dont know if I understand question correctly. Do you want to implement something like this ?

      public DataTable  CreateDataTable(Dictionary<string,Type> columns)
      {
            DataTable dt = new DataTable();
            foreach( var key in columns)
            {
                var column = dt.Columns.Add();
                column.ColumnName = key.Key;
                column.DataType = key.Value;
            }
            return dt;

        }


        public void CreateNewDataTable()
        {
            var columns = new Dictionary<string, Type>()
                {
                    {"column", typeof (string)}
                };
            var dt = CreateDataTable(columns);
        }

Upvotes: 2

Related Questions