在DataTable中,
如何跟据某列的得到它所在的行号?
比如我有一个四行三列的表T,
number name  age sex
101     张三  12  男
102     李四  13  男
103     王五  14  男
我通过第二列为关键字查找"李"姓的人名字所在的行,
在C#的DataTable中如何操作

解决方案 »

  1.   

    string record="";
    for(int i=0;i<table.rows.count;i++)
    {
      int s=0;
      string temp_name= table.rows[i]["name"].ToString();
      s=temp_name.indexof("李");
      if(s!=-1)
      {
       record = record+s.ToString()+","; 
      }
    }
    record =record.substring(0,record.length-1);
      

  2.   

    fa cuo  错了
    string record="";
    for(int i=0;i<table.rows.count;i++)
    {
      int s=0;
      string temp_name= table.rows[i]["name"].ToString();
      s=temp_name.indexof("李");
      if(s!=-1)
      {
       record = record+i.ToString()+","; 
      }
    }
    record =record.substring(0,record.length-1);
      

  3.   

    bsh_ly,如果没找到的话,你这里分抛出长度不够的异常,哈哈,应该还加一句。
    if (record.length >0)
    {
    record =record.substring(0,record.length-1);
    }
      

  4.   

    你可以用Find来查找,例如:
    DataTable dt1 = new DataTable();
    dt1.Columns.Add("number ", typeof(int));
    dt1.Columns.Add("Name", typeof(string));
    dt1.Columns.Add("age", typeof(int));
    dt1.Columns.Add("sex", typeof(string));
    dt1.PrimaryKey = new DataColumn[] { dt1.Columns[1] };dt1.Rows.Add(101,"张三", 12,"男");
    dt1.Rows.Add(102, "李四", 13, "男");
    dt1.Rows.Add(103, "王五", 14, "男");DataRow row = dt1.Rows.Find("李四");
    if (row!=null)
    {
        //找到了记录;
    }
      

  5.   

    用 DataTable.Select 来做:DataRow[] rows = dt1.Select("Name LIKE '李%'");
      

  6.   

    如果我只想得到他所在的行呢?因为我把这个表显示在DataGrid里面,通过查找定位到这一行.
      

  7.   

    你在DataTable产生时,按照想要查找的字段进行排序一下:dtSample.Sort="字段名";
    然后:dtSample.Rows.Find方法返回当前行的索引,若为-1,则没找到;否则就找到了,
    最后:dtSample.Rows[Index]["列名"].ToString()就可以获取值了。
      

  8.   

    楼上的,DataTable.Rows.Find()方法是返回DataRow类型的,
    要返回行号可以用DataView.Find();
    先排序,再用myTable.DefaultView.Find(要找的字);就OK了,
    但是找到后调用DataGrid.Select(index)时是默认是多选,怎么设置它成单选?