如何从tableadapter获取单元格值的行索引?

时间:2013-07-08 11:46:36

标签: c# wpf

enter image description here我想按单元格值学习行索引。我知道细胞价值" E003"。如何学习行包含单元格值的行索引" E003"?我需要7而不是11。

var table =TableAdapter.GetData();
var resultRow = table.Rows["I need row index. But I know just cell value"]; 

2 个答案:

答案 0 :(得分:0)

基于TableAdapter Overview,您可以get the underlying DataTable想要查询var table = TableAdapter.GetData()

通过搜索具有给定值

的DataTable来查找行的索引

下面的行显示了如何通过该行的主键查找某一行的索引。首先从DataTable获得collection of rows然后您可以使用Find()方法按给定值搜索行。

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: ");

基础数据与截图类似

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;
}

由于您对列Emp_Code几乎没有提及,我假设它可以用作数据表的主键。

linqpad演示程序的屏幕截图

下面你可以看到上面的代码在linqpad中执行

enter image description here

如果您无法使用Emp_Code作为主键,则可以在问题How to find a value in DataTable in C#?

中找到所需的信息

答案 1 :(得分:-1)

我今天找到了一个解决方案。

            var table = TableAdapter.GetData().Select(s => new { s.Index })
                                  .AsEnumerable()
                                  .Select((s, counter) => new
                                  {
                                      s.Index,
                                      counter = counter + 1

                                  });

            foreach (var item in table)
            {
                if (item.Index == Emp_ID)
                {                        
                    //do something

                    break;
                }
            }
相关问题