简体   繁体   中英

DatagridView Selected Row Error

What is wrong w/my code?

this.comboBox1.SelectedIndex = _f3.dataGridView2.SelectedRows[0].Index;

my datagrid is in form3 and my combobox is in form 2. HOW could I implement something like this?

Instead, you declare one public integer in form2 and when you want to get the selected row index of the datagridview you can use the CurrentRowIndex property to get the index of the datagridview selected row like, in form3 you get the selectedindex global varaible from form2 and assign the CurrentRowIndex, or declare a public method which should return the selected row index when ever required

In form2 you write something like

  private int selectedindex {get; set;}
    selectedindex = _f3.GetSelectedIndex();
    this.comboBox1.SelectedIndex = selectedindex;

In form3 you write the method like

 public int GetSelectedIndex()
    {
         int selectedIndex = 0;
         try
         {
           if(dataGridView2.SelectedRows.Count > 0)
           {
              selectedIndex = dataGridView2.CurrentRow.Index;
           }
         }
         catch
         {
          return 0;
         }
      return selectedIndex;
    }

EDIT:

You can use instead

dataGridview2.CurrentRow.Index

In form3 under the SelectionChanged event of datagridview you do the following thing

    private void dataGridView2_SelectionChanged(object sender, EventArgs e)
    {
        selectedindex = dataGridView2.CurrentRow.Index;
    }

and also declare the selectedindex as an integer as a public variable like

public int selectedindex {get; set;}

and in form2 directly get the selectedindex by using the global variable like below,

this.comboBox1.SelectedIndex = _f3.selectedindex;

get the selectedindex when ever required.

将datagridview2的Modifiers属性更改为Public

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM