【问题标题】:Adding button in datagridView not working onClick event在datagridView中添加按钮不起作用onClick事件
【发布时间】:2014-12-17 14:16:21
【问题描述】:

我有这个从对象获取数据的 datagridView。 我添加这样的列:

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

我添加了一个 onclick 事件,但它不起作用,我错过了什么吗?

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();
    } 
}

我收到一个错误:索引超出范围。必须为非负数且小于集合的大小。

【问题讨论】:

  • CellClick 活动中检查您的ColumnIndexRowIndex
  • 我应该检查什么?如果我不添加新列,则单击事件有效,但不适用于新列@vallabha
  • 当您单击已添加的按钮时,会引发异常或事件本身未触发。
  • @vallabha,是的,我明白了:索引超出范围。必须为非负数且小于集合的大小。
  • 然后在您的if 条件处设置一个断点并检查CellClick 事件中的ColumnIndexRowIndex

标签: c# datagridview


【解决方案1】:

您可以使用is 运算符来检查:“您的单元格是否是其他单元格的按钮”

并使用CellContentClick 而不是CellClick,因为如果用户单击按钮的填充,您的事件不会引发并等待单击按钮。

因此,您可以使用此活动

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

【讨论】:

  • 谢谢,不过有个问题,我如何从所选行中获取第一列的值?
  • 这是另一个问题,但我回答你听到了。你可以使用dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value = "Changed Me";
【解决方案2】:

也许这是一个缺陷但是:

colUsers.Name = ""; 

将您的列名设置为空字符串而不是“用户”。属性 Text 与属性 Name 不同。

colUsers.Name = "Users";

编辑:常量字符串

当您想在代码中使用字符串值时,请开始使用常量引用。这会将您的字符串值保留在 1 个位置,而不是在您可能提供错误信息的情况下一直重复使用它们,从而导致错误的结果。

例如

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();
}

编辑:完整的属性列表

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2017-07-18
    • 2013-12-13
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多