How to get last column name from a datatable

I am passing a datatable to function like below:

public static DataTable FindingRowOrder(DataTable mynew) 
{
  // Code 
}

My question is how to get the last column name for the mynew dataTable?

Answers


int count= mynew.Columns.Count;
var lastColumn = mynew.Columns[count - 1];
string columnname= lastColumn.ColumnName;

Use LINQ

 var lastcol = mynew.Columns.Last().Name;

Alternatively you can access it using index.

var lastcol = mynew.Columns[mynew.Columns.Count - 1].Name;

EDIT: added .Name property.


Try this

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("FirstColumn1", Type.GetType("System.String"));
        dt.Columns.Add("FirstColumn2", Type.GetType("System.String"));
        dt.Columns.Add("FirstColumn3", Type.GetType("System.String"));
        dt.Columns.Add("FirstColumn4", Type.GetType("System.String"));
        dt.Columns.Add("FirstColumn5", Type.GetType("System.String"));
        dt.Columns.Add("FirstColumn6", Type.GetType("System.String"));
        string result = GetLastColumnn(dt);
    }
    private string GetLastColumnn(DataTable dt)
    {
        string str = dt.Columns[dt.Columns.Count-1].ColumnName;
        return str;
    }

Try this:

var lastcol = mynew.Columns[mynew.Columns.Count - 1].Name;

Need Your Help

Can't install Pip Packages in El Capitan (10.11)

python macos pip osx-elcapitan

Okay, so I have brew, and I've brew reinstalled python since El Capitan.