Volkan
Volkan

Reputation: 546

C# DataTable as a class

I need to have a datatable in C# accessible by other methods... and I am told that I need to make a datatable as a class, not as a method, like I did in the example below:

//my existing datatable method     
public DataTable Conditions(){
        DataTable dtConditions = new DataTable(); 

        DataColumn firstParameterID = new DataColumn("firstParameterID ", typeof(int));
        dtConditions.Columns.Add(firstParameterID);

        DataColumn secondParameterID = new DataColumn("secondParameterID ", typeof(int));
        dtConditions.Columns.Add(secondParameterID ); 
         /*
         * more columns and rows...
         */
        return dtConditions;
    }

My question is: How do I put it or can I put it in a separate class file named dataTableConditions.cs....

I created a class file and here is what I have, but what next?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace myHomeworkProject
{
    class dataTableConditions
    {
        //How do I make this class and later how can I access its rows, I mean, how can I assign values to these rows later from other methods?
    }
}

Thank you!

Upvotes: 0

Views: 2428

Answers (1)

Moerwald
Moerwald

Reputation: 11254

Since you're creating the following

 DataTable dtConditions = new DataTable(); 

You shoulk create a DataTable class. The class can look like:

using  System.Collections.Generic;

namespace someNamespace {

    public class DataTable {

        public List<DataColumn> Columns {get;set;}
    }

}

Columns is a List object storing the different DataColumns. You can also create a List property that stores the different rows.

.Net framework also includes a default implementation of a data table class. This link shows you how the "API" of the class looks like. This link describes how to write your own datatable class.

Hope that helps.

Upvotes: 1

Related Questions