Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7977017
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T09:04:20+00:00 2026-06-04T09:04:20+00:00

I am trying to Maintain Selected Row of the DataGridView Control after refreshing Data.

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T09:04:22+00:00Added an answer on June 4, 2026 at 9:04 am

    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]

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to maintain a collection of objects based on their URI: public class
I'm trying to maintain a list of objects in a Manager class in C#.
I'm trying to maintain a dictionary of configurations. Here is my abstract class. [Serializable]
I'm trying to maintain state on an object by doing something like this: obj
I am trying to maintain code that compiles on lots of different systems. I've
I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:
I'm trying to maintain one repository, most everything in my code base is source,
I'm brand new to log4net, and I'm trying to maintain some legacy code that
I'm trying to maintain someone else's code right now where that person is a
I'm trying to maintain some Wix code, and am getting the following warning: warning

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.