Maintaining Selected Row of the DataGridView Control after refreshing Data

Posted by user575219 on Stack Overflow See other posts from Stack Overflow or by user575219
Published on 2012-05-23T04:08:25Z Indexed on 2013/11/03 9:54 UTC
Read the original article Hit count: 348

Filed under:

I am trying to Maintain Selected Row of the DataGridView Control after refreshing Data. This is my code

 public partial class frmPlant : Form
    {
        string gSelectedPlant;

     private void frmPlant_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.DataSource = bindingSource1;
            FillData();

            dataGridView1.DataMember = "Table";
}
 private void FillData()
        {
            ds = _DbConnection.returnDataSet(_SQlQueries.SQL_PlantSelect);
            bindingSource1.DataSource = ds.Tables[0];
        }
 public DataSet returnDataSet(string txtQuery)
        {
            conn.Open();
            sqlCommand = conn.CreateCommand();
            DB = new SQLiteDataAdapter(txtQuery, conn);
            DS.Reset();
            DB.Fill(DS);
            conn.Close();
            return (DS);
        }
  private void dataGridView1_Selectionchanged(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                gSelectedPlant = dataGridView1.SelectedRows[0].Cells["PlantId"].Value.ToString();
            }
        }

        private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            int selectedIndex;
            if (!string.IsNullOrEmpty(gSelectedPlant) && e.ListChangedType == ListChangedType.Reset)
            {
                if (ds.Tables.Count > 0)
                {
                    selectedIndex = bindingSource1.Find("PlantId", gSelectedPlant);
                    if (selectedIndex <= 0)
                        selectedIndex = 0;
                    dataGridView1.Rows[selectedIndex].Selected = true;
                }
                else
                {
                    gSelectedPlant = string.Empty;
                }
            }
        }
    }

It is still not able to maintain the rowindex of the selected row. It scrolls to row1. Here's the blog I used http://www.makhaly.net/Blog/9

Suppose, I select a row on Form1(where all this code is) and go on the next form, which shows me detailed info abt the particular Plant . If I come back to this first form again,by pressing the back button, the row is reset to 1. gSelectedPlant takes a value 1 and selectedindex = 0. This makes sense but I am not yet able to figure out how to maintain the value of gSelectedPlant. Yes it takes a null intitally but on databindingcomplete it becomes 1.

© Stack Overflow or respective owner

Related posts about c#