Select row programatically in GridView that has databound

2 posts, 1 answers
  1. Attila
    Attila avatar
    22 posts
    Member since:
    Oct 2016

    Posted 21 Sep 2017 Link to this post

    I have a GridView in my Winform application and its datasource is bound to a list of custom objects. Let's assume this custom object has 2 fields: name and ID, so the gridview has also 2 columns: name and ID. (name first, then the ID). 

     

    Now I want to select the row that has the given ID.

    How can I select it? gridView1.Rows[0].IsSelected = true; is not OK here, because I don't know the index of the row.

    The GridView has DataSource set this way (of course this is a simple example):

     

    List<MyObject> myList=new List<MyObject>();
    myList.Add(new MyObject("name1", 1));
    myList.Add(new MyObject("name2", 2));
    gridView1.DataSource = myList;

    Thanks for your help

  2. Answer
    Dess | Tech Support Engineer, Sr.
    Admin
    Dess | Tech Support Engineer, Sr.  avatar
    3532 posts

    Posted 22 Sep 2017 Link to this post

    Hello, Attila, 

    Thank you for writing.  

    It is necessary to iterate the RadGridView.Rows collection and find which row exactly has the searched ID. Then, you can select the row programmatically that matches the search criteria. Note that each row has Cells collection where you can access the respective cell and get its Value accordingly.

    Here is a sample code snippet:  
    public RadForm1()
    {
        InitializeComponent();
        List<MyObject> myList = new List<MyObject>();
     
        myList.Add(new MyObject("name1", 1));
        myList.Add(new MyObject("name2", 2));
        myList.Add(new MyObject("name3", 3));
        this.radGridView1.DataSource = myList;
     
        foreach (GridViewRowInfo row in this.radGridView1.Rows)
        {
            if ((int)row.Cells["Id"].Value==2)
            {
                row.IsSelected = true;
                row.IsCurrent = true;
                break;
            }
        }
    }
     
    public class MyObject
    {
        public string Name { get; set; }
        public int ID { get; set; }
     
        public MyObject(string name, int iD)
        {
            this.Name = name;
            this.ID = iD;
        }
    }

    I hope this information helps. Should you have further questions I would be glad to help.

    Regards,
    Dess
    Progress Telerik
    Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Back to Top