简体   繁体   中英

Getting the selected row from dataGridView1

I have a dataGridView1 on my Wondows Form Application. I have populated the dataGridView1 with a list of strings. This all works great. But...

I need to be able to grab the row the user is selected on and I can't seem to do it. My code just gives me an error, written below.

I have copied GridViewRow form the msdn site.

private void editButton_Click(object sender, EventArgs e) {
        GridViewRow row =  dataGridView1.SelectedRow;

        //This is what I have been using before with a list box.
        if (itemList.SelectedIndex >= 0) {
            int newInt = itemList.SelectedIndex;
            Form form = new NewItemW(selectedFolder, this, items[newInt], WindowEnum.ItemEdit);
            form.Show();
        }
    }

I have tried this but I am getting the error: "The type or namespace 'GridViewRow' could not be found."

My basic question is how do I get this to work?

Assuming you are using a Winforms DataGridView you should do it like this:

private void editButton_Click(object sender, EventArgs e) 
{
   if (DataGridView1.SelectedRows.Count > 0)
   {
      DataGridViewRow row =  dataGridView1.SelectedRows[0];
      if (itemList.SelectedIndex >= 0) 
      {
         int newInt = itemList.SelectedIndex;
         Form form = new NewItemW(
                         selectedFolder, this, items[newInt], WindowEnum.ItemEdit);
         form.Show();
      }
   }
}

By copying from that link you have mixed the WPF Controls and their code with Winforms. Often folks mix up just the names DataGridView vs GridViewRow , but you have also copied the wong Property SelectedRow . Instead use the first element of the SelectedRows collection. Also always check or else the array acess will crash..

you are using the web control System.Web.UI.WebControls.WebControl.GridViewRow, it must be hosted in a web page. For windows form use the System.Windows.Forms.DataGridViewRow control.

http://msdn.microsoft.com/en-us/library/vstudio/system.windows.forms.datagridviewrow(v=vs.110)

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