Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

c# - How can I get row index from tableadapter by cell value?

enter image description hereI want to learn row index by cell value. I know cell value "E003". How can I learn row index that row include cell value "E003"? I need 7 not 11.

var table =TableAdapter.GetData();
var resultRow = table.Rows["I need row index. But I know just cell value"]; 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Based on TableAdapter Overview you can get the underlying DataTable that you would like to query like this var table = TableAdapter.GetData()

Find Index of Row by searching a DataTable with a given value

The lines below show how you can find the Index of a certain row by Finding it via the primary key of that row. First you get a collection of rows from the DataTable and then you can use the method Find() to search a row by the given value.

DataRowCollection rowCol = GetDataTable().Rows; 
rowCol.Dump("Content for RowCollection: ");
// find row by value of primary key
// for it to work Emp_Code as to be set as primary key column
DataRow foundRow = rowCol.Find("E003"); 

int indexOfRow = rowCol.IndexOf(foundRow);
indexOfRow.Dump("zero based RowIndex is: ");

The underlying data looks similar to your screenshot

private DataTable GetDataTable()
{
   DataTable table = new DataTable("NameIsOptional");
   table.Columns.Add(new DataColumn("Emp_Id", typeof(int)));
   table.Columns.Add(new DataColumn("Emp_Code", typeof(string)));
   table.Columns.Add(new DataColumn("L_Name", typeof(string)));
   // set Column 'Emp_Code' as primary key column
   table.PrimaryKey = new DataColumn[] {table.Columns["Emp_Code"]};

   table.Rows.Add(1, "E001", "dave");
   table.Rows.Add(2, "E002", "mandle");
   table.Rows.Add(3, "E007", "sarana");
   table.Rows.Add(4, "E004", "poyekar");
   table.Rows.Add(5, "E005", "suryawanshi");
   table.Rows.Add(9, "E006", "survey");
   table.Rows.Add(11, "E003", "singh");

   return table;
}

Since you said little about the column Emp_Code i assume that it can be used as the primary key of the datatable.

Screenshot of linqpad demo programm

Below you can see the above code executed in linqpad

enter image description here

If you can not use Emp_Code as a primary key you may find the information you need in the question How to find a value in DataTable in C#?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...