简体   繁体   中英

Adding button in datagridView not working onClick event

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.

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...";
}

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

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