Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

DataTable in C# – named rows

Is it possible to give name for each row in DataTable? I would like to simply refer to the given cell in DataTable by typing

myDataTable.Rows["Row1"]["Column1"]

instead passing Row Index as int.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t do this, because rows are only indexed by their row index. Columns are indexed by their column index and column name. If you need to reference rows by a name, you must create your own index:

var rowNameToIndexMap = new Dictionary<string, int>();
var dataTable = new DataTable();
      
/* Index a row */
var row = dataTable.NewRow();
dataTable.Rows.Add(row);
var rowName = "first row";
rowNameToIndexMap.Add(rowName, dataTable.Rows.Count - 1);

/* Retrieve first row by its row name */
if (rowNameToIndexMap.TryGetValue(rowName, out int rowIndex))
{
  var firstRow = dataTable.Rows[rowIndex];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading