Search code examples
c#winformsdatagridview

C# - How to get the current row index of a DataGridView from a different Form?


I currently have two forms--my main form, Form1, which has a DataGridView who's data source is a BindingList. Form2 is accessed via a button press, and is filled with textboxes populated with data from said BindingLists. For example, the code for that (in Form2) looks like the following:

Textbox1.DataBindings.Add(new Binding("Text",SomeClass.SomeBindingList[0], "Field2"));
Textbox2.DataBindings.Add(new Binding("Text", SomeClass.SomeBindingList[0], "Field2"));

This will populate Textbox1 and Textbox2 with stuff from index 0 of the BindingList. Now, I obviously want SomeClass.SomeBindingList[0] to use, instead of 0, the currently selected row number of the DataGridView in Form1.

In order to achieve this, I wrote the following code in Form2:

Form1 firstform = new Form1();
int testIndex = firstform.dataGridView1.SelectedRows[0].Index;

However, when I run the program, I get the error:

System.ArgumentOutOfRangeException: 'Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: testIndex

When assigning dataGridView1.SelectedRows[0].Index to an integer in Form1, I have no issue returning the correct value. I've even tried passing it FROM Form1 to a public int in Form2 but the same issue happens.

Basically what I want to know is if what I'm trying to achieve is possible, and how. Thanks!


Solution

  • try this

    Form1.cs

    private void buttonOpenForm2_Click(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedRows.Count > 0)
        {
            int selectedIndex = dataGridView1.SelectedRows[0].Index;
           
            Form2 form2 = new Form2(this, selectedIndex);
            form2.Show();
        }
        else
        {
            MessageBox.Show("Please select a row first.");
        }
    }
    

    Form2.cs

    public partial class Form2 : Form
    {
        private Form1 _form1;
        private int _selectedIndex;
    
        public Form2(Form1 form1, int selectedIndex)
        {
            InitializeComponent();
            _form1 = form1;
            _selectedIndex = selectedIndex;
    
            if (_selectedIndex >= 0 && _selectedIndex < SomeClass.SomeBindingList.Count)
            {
                Textbox1.DataBindings.Add(new Binding("Text", SomeClass.SomeBindingList[_selectedIndex], "Field1"));
                Textbox2.DataBindings.Add(new Binding("Text", SomeClass.SomeBindingList[_selectedIndex], "Field2"));
            }
            else
            {
                MessageBox.Show("Invalid row selected.");
            }
        }
    }