Steam
Steam

Reputation: 9856

Need help to get DataColumn of a DataTable

I want to get a column with a given name into a DataColumn object so that I can iterate over the rows of that column. My code is given below. What replacement do I make in the line marked pseudocode ?

I guess you can safely ignore all this code and read the main() method code right away. Specifically, go to line -

DataColumn dc = getColumn("YourColumnName"); //PSEUDOCODE

The code is -

using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Xml;
using System.Data.OleDb;

namespace ST_54125473205c4f38b466c43a15bc9d79.csproj
{
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {

        #region VSTA generated code
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

        public void Main()
        {
            // TODO: Add your code here
            Dts.TaskResult = (int)ScriptResults.Success;
            OleDbDataAdapter oleDA = new OleDbDataAdapter();
            DataTable dt = new DataTable();
            DataColumn col = null;
            DataRow row = null;
            string strMsg = null;

            oleDA.Fill(dt, Dts.Variables["myADO_Recordset"].Value);

            foreach (DataRow dtRow in dt.Rows)
            {
                DataColumn dc = getColumn("YourColumnName"); //PSEUDOCODE

                    var field1 = dc.ColumnName;
                    MessageBox.Show(field1);
            }

            Dts.TaskResult = (int)ScriptResults.Success;
        }
    }
}

Upvotes: 2

Views: 3856

Answers (2)

Edper
Edper

Reputation: 9322

If you want the Column name use Columns property in your DataTable instead of getting the Rows, like:

 foreach (DataColumn dc in dt.Columns)
 {
     String field1 = dc.ColumnName;
     MessageBox.Show(field1);
 }

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166336

You should be able to use DataTable.Columns Property

Gets the collection of columns that belong to this table.

and use the string indexer

Gets the DataColumn from the collection with the specified name.

So something like

DataColumn dc = dt.Columns["YourColumnName"];

Upvotes: 1

Related Questions