1

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.

user575219
  • 2,346
  • 15
  • 54
  • 105
  • 1
    Did you try putting the breakpoint on DataBindingComplete and see if it goes through the checks, also if it finds SelectedIndex value – Habib May 23 '12 at 04:46
  • Put the breakpoint and check the sequence of event fired, dataGridView1_DataBindingComplete event is fired first. So, i think that's why 'gSelectedPlant' variable not maintaining the proper value. – Talha May 23 '12 at 05:25
  • Did you try to add the boolean guarding the execution of SelectionChanged? – Francesco Baruchelli May 23 '12 at 14:26

3 Answers3

1

Have you tried debugging it? I can't try it since I don't know when you call FillData, apart from the loading event of the forms, but I don't think it is the point where you have the problem. I suspect that the problem is that you always skip the selection part of dataGridView1_DataBindingComplete because gSelectedPlant is always empty or set to the first row.

This usually happens because SelectionChanged is fired many more times than you think, in particular it is called before DataBindingComplete. This means that when you call FillData you should "instruct" your form to ignore the SelectionChanged events until the DataBindingComplete has been executed. This can be done modyfing your code something like this:

public partial class frmPlant : Form
{
     string gSelectedPlant;
     bool ignoreSelChg = false;  // <- added this bool    

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

            dataGridView1.DataMember = "Table";
     }

     private void FillData()
     {
            ignoreSelChg = true; // <- set the bool, SelectionChanged won't do anything now

            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 (ignoreSelChg)  // <- don't do anything before DataBindingComplete
                return;

            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)
            {
                ignoreSelChg = false; // <- reset the bool, SelectionChanged get executed again

                if (ds.Tables.Count > 0)
                {
                    selectedIndex = bindingSource1.Find("PlantId", gSelectedPlant);
                    if (selectedIndex <= 0)
                        selectedIndex = 0;
                    dataGridView1.Rows[selectedIndex].Selected = true;
                }
                else
                {
                    gSelectedPlant = string.Empty;
                }
            }
        }
    }

You can take a look at the posts of Mark Rideout here: [http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/01f937af-d0d0-4de5-8919-088e88c5af77/][1]

Francesco Baruchelli
  • 7,320
  • 2
  • 32
  • 40
  • I have a back button from another form2 to this one form1. Once I click the back button, I reload the grid(Filldata). This is where I need to maintain the selected row. Yes u r correct. gSelectedplant is either null or set to 1 – user575219 May 23 '12 at 05:46
  • @ Francesco Baruchelli. It does not. Myform.show is what is causing the problem. http://stackoverflow.com/questions/10761154/form-show-causing-to-loose-row-selection. Please help me. It is due today – user575219 May 26 '12 at 01:09
  • @ Francesco Baruchelli: Thanks man.. finally got this thing to work with ur code and a slight modification in the way I am selecting the current row. I should be using dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0]; dataGridView1.Rows[i].Selected = true; } – user575219 May 26 '12 at 06:20
0
//public area
 int selectedID,rowIndex, scrollIndex;
 bool IsSelectedRow;

 private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
  {
      if (e.RowIndex < 0)
          return;
      selectedID = (int)DataGridView1.SelectedRows[0].Cells[0].Value;
      scrollIndex = DataGridView1.FirstDisplayedScrollingRowIndex;
      IsSelectedRow = true;
    }

    private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
            {
                if (IsSelectedRow)
                {
                    foreach (DataGridViewRow row in DataGridView1.Rows)
                    {
                        if (row.Cells[0].Value.ToString().Equals(selectedID.ToString()))
                        {
                            rowIndex = row.Index;
                            break;
                        }
                    }
                    DataGridView1.Rows[rowIndex].Selected = true;
                }           
            }
R.Akhlaghi
  • 729
  • 1
  • 12
  • 23
-1

Did you check bindingSource1.Find("PlantId", gSelectedPlant); is returning the correct row index ?

Sudhakar B
  • 1,465
  • 9
  • 16