我的DataGirdView有一列为ID,我想选中ID列中值为"XXX"的一列,该如何做?

解决方案 »

  1.   

    不好意思写错了
    我的DataGirdView有一列为ID,我想选中ID列中值为"XXX"的一行,该如何做?
      

  2.   

    to:flyingdream123
    能不能详细说一下?
      

  3.   

    我想LZ是想根据ID的值来使datagrid的相应行处于选中状态吧?如果是这个目的,可以用我写的这段代码试试。for(int i=0;i<this.dataGrid1.BindingContext[this.dataGrid1.DataSource].Count;i++)
    {
    this.dataGrid1.BindingContext[this.dataGrid1.DataSource].Position=i;
    DataRowView currow=(DataRowView)this.dataGrid1.BindingContext[this.dataGrid1.DataSource].Current;
    if(currow["id"].ToString="xxx") dataGrid1.Select(i);
    }
      

  4.   

    如果绑定的是DataTable..
    DataTable dt=  this.dataGridView1.DataSource as DataTable ;
    DataRow[] drs = dt.Select("ID=xxx");
    drs[0]就是你想要的行....
      

  5.   

    LZ不只是要在表中检索行,而是还要在DATAGRID中把相应行设为选中状态吧。
      

  6.   

    谢谢syczx(笑笑) 
    用的是遍历的办法,我明白了
      

  7.   

    to 我的DataGirdView有一列为ID,我想选中ID列中值为"XXX"的一行,该如何做?遍历太麻烦了,而且在点击列头排序后,方法会失效。正确的办法是通过DataView.Find来获得,
    大致如下:
    DataView dv = new DataView( yourDataTable, currentSortString, null, DataViewRowState.CurrentRows );
    int nRowIndex = dv.Find( yourIDValue );
    yourGridView.Select( nRowIndex );
      

  8.   

    这个方法我也想过。可是我不知道怎么保证表行号与datagrid的行号对应上。上回我写一段程序的时候就遇到这个问题:从datagrid取得选中状态的行号,用这个行号去操作表,却把表的别的行的数据修改了,就是说两者行号不对应。因此,没有办法才用了这个遍历的办法。楼上的,这个问题是怎么办到的?我也相信一定有办法使两者行号对应上,只是我不知道。
      

  9.   

    用BindingSource.Find()玩。把Oracle改为Sql或OleDb...private BindingSource bs;
    public Form1()
    {
         InitializeComponent();
    }private void Form1_Load(object sender, EventArgs e)
    {
                OracleConnection conn = new OracleConnection();
                conn.ConnectionString = "Data Source=***;User ID=***;Password=***";            OracleCommand cmd = new OracleCommand();
                cmd.Connection = conn;
                cmd.CommandText = "select ***, XZCH, ***, *** from TABLE";            DataTable dt = new DataTable();
                conn.Open();
                dt.Load(cmd.ExecuteReader(CommandBehavior.CloseConnection));
                conn.Dispose();            bs = new BindingSource();
                bs.DataSource = dt;            dataGridView1.DataSource = bs;
    }private void button1_Click(object sender, EventArgs e)
    {
                bs.Position = bs.Find("XZCH", textBox1.Text);
                
    }
      

  10.   

    对了,和问题无关。上面代码中DataTable可以不要。
    直接
    bs.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
      

  11.   

    哦,SORRY,还是需要DataTable的,好像和IBindingListView接口有关,上面直接绑定到BindingSource后用Find()方法无效~,
      

  12.   

    to 这个问题是怎么办到的?我也相信一定有办法使两者行号对应上,只是我不知道。其实绑定datatable到datagrid,最终会以dataview的形式绑定,那么在datagrid中排序之类的操作,就是dataview的排序,因此为了找到排序后的位置,只要通过datatable按照同样的排序方式产生dataview,然后在其中查找记录的相对位置即可返还到datagrid的位置。