Funlamb
Funlamb

Reputation: 625

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?

Upvotes: 0

Views: 239

Answers (2)

TaW
TaW

Reputation: 54433

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..

Upvotes: 1

rdenisi
rdenisi

Reputation: 139

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)

Upvotes: 0

Related Questions