0

I have this datagridView that takes data from an object. I add columns like this:

dataGridView1.CellClick += dataGridView1_CellClick;
DataGridViewButtonColumn colUsers = new DataGridViewButtonColumn();
colUsers.UseColumnTextForButtonValue = true;
colUsers.Text = "Users";
colUsers.Name = "";
dataGridView1.Columns.Add(colUsers);

And I add an onclick event, but it's not working, am I missing something?

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{

    if (e.RowIndex > -1 && dataGridView1.Columns[e.ColumnIndex].Name == "Users")
    {
        name = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
        gtUserDetails.ShowDialog();
    } 
}

I get an error: Index was out of range. Must be non-negative and less than the size of the collection.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Perf
  • 23
  • 1
  • 8

2 Answers2

1

you can use is operator for checking that: "is your cell a button of other"

and use CellContentClick instead CellClick, because if user click on padding of your button, your event don't raise and wait for clicking ON your button.

Therefor, you can use this event

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1[e.ColumnIndex,e.RowIndex] is DataGridViewButtonCell)
        (dataGridView1[e.ColumnIndex, e.RowIndex] as DataGridViewButtonCell).Value = "You Clicked Me...";
}
Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40
  • thank you, one question though, how do i get the value of the first column from the row selected? – Perf Oct 22 '14 at 08:02
  • this is another question, But I answer you hear. You can use `dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value = "Changed Me";` – Mehdi Khademloo Oct 22 '14 at 08:14
0

Perhaps this is a flaw BUT:

colUsers.Name = ""; 

sets your columnname on an empty string instead of "Users". the property Text isn't the same as property Name.

colUsers.Name = "Users";

EDIT: Constant strings

Whenever you want to use string values inside your code, plz start using a Constant reference. This will keep your string values in 1 place instead of reusing them all the time where the possibility lays that you give in the wrong info, resulting in wrong results.

for example

const readonly string UserbuttonName = "Users";

private void CreatebuttonName()
{
  colUsers.Name = UserbuttonName;
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
 if (e.RowIndex > -1 && dataGridView1.Columns[e.ColumnIndex].Name == UserbuttonName)
  DoSomething();
}

EDIT: a complete list of properties

Datagridviewbutton column properties : http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewbuttoncolumn_properties(v=vs.110).aspx

Schuere
  • 1,579
  • 19
  • 33