using System; using System.Data.SqlClient; namespace GetOrdinalExample { class Program { static void Main(string[] args) { string connectionString = "Data Source=(local);Initial Catalog=TestDB;Integrated Security=True;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string query = "SELECT Column1, Column2, Column3 FROM TestTable"; SqlCommand command = new SqlCommand(query, connection); using (SqlDataReader reader = command.ExecuteReader()) { int column1Index = reader.GetOrdinal("Column1"); int column2Index = reader.GetOrdinal("Column2"); int column3Index = reader.GetOrdinal("Column3"); while (reader.Read()) { Console.WriteLine(reader.GetString(column1Index)); Console.WriteLine(reader.GetInt32(column2Index)); Console.WriteLine(reader.GetDateTime(column3Index)); } } } } } }
using System; using System.Data; namespace GetOrdinalExample { class Program { static void Main(string[] args) { DataTable table = new DataTable(); table.Columns.Add(new DataColumn("Column1", typeof(string))); table.Columns.Add(new DataColumn("Column2", typeof(int))); table.Columns.Add(new DataColumn("Column3", typeof(DateTime))); DataRow row = table.NewRow(); row["Column1"] = "value1"; row["Column2"] = 123; row["Column3"] = DateTime.Now; table.Rows.Add(row); int column1Index = table.Columns.IndexOf("Column1"); int column2Index = table.Columns.IndexOf("Column2"); int column3Index = table.Columns.IndexOf("Column3"); foreach (DataRow dataRow in table.Rows) { Console.WriteLine(dataRow.ItemArray[column1Index]); Console.WriteLine(dataRow.ItemArray[column2Index]); Console.WriteLine(dataRow.ItemArray[column3Index]); } } } }In this example, we create a DataTable and add columns to it. We then create a DataRow, set the values of its columns, and add it to the DataTable. We then use the IndexOf method to get the index of each column in the DataColumnCollection, and use the ItemArray property to retrieve the values of each column. Package library: System.Data