Click here to Skip to main content
15,891,473 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
in a datatable there are number of columns ,out of which i want to select a particular coulmn.

What I have tried:

i have tried number of ways ,by searching on google
Posted
Updated 26-Jul-16 1:36am

You can use the Columns collection:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    DataTable dt = new DataTable();
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 20 Title FROM Videos ORDER BY Title ASC", con))
        {
        da.Fill(dt);
        }
    DataColumn dc = dt.Columns[0];
    }

But that won't give you access to the actual values in each column of the table.
For that, you need to iterate the Rows collection:
C#
foreach (DataRow row in dt.Rows)
    {
    Console.WriteLine(row[0]);
    }
 
Share this answer
 
You can access the column from the rows of the DataTable. Just like any data table, you first access the rows and then you access their columns.
C#
var table = GetYourDataTable();

foreach (var row in table) {
   var column = row["ColumnName"];

   // Use the column
}

The table would provide access to rows and you can then access each column individually using their name or the index they are at. This MSDN guide is not about getting the columns but it gives you an idea of how you can get the columns (for getter and setter actions). Adding Data to a DataTable[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900