如何获取单元格值按钮在数据网格 C# 中单击

本文关键字:数据网 数据 网格 单击 按钮 何获取 获取 单元格 | 更新日期: 2023-09-27 18:35:24

当我

单击button时,我想在ShowRichMessageBox中显示特定的单元格值,但如果单击行上的任意位置,此事件将显示单元格值...!

这是怎么了.....如何解决上述问题???

我有一些很大的日志值,但它已经加载到单元格中,所以, Is it possible to expand the row when i select a particular row in the datagridview???

 public LogView()
    {
        InitializeComponent();
        this.dataGridView2.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView2_buttonCol);
        bindingList = new SortedBindingList<ILogItemView>();
        dataGridView2.DataSource = bindingList;
        this.dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        this.dataGridView2.MultiSelect = false;
        var buttonCol = new DataGridViewButtonColumn(); // The button to display a particular cell value when clicks//
        buttonCol.Name = "ButtonColumnName";
        buttonCol.HeaderText = "Show";
        buttonCol.Text = "View";
        buttonCol.UseColumnTextForButtonValue = true;    
        dataGridView2.Columns.Add(buttonCol);
    }
    private void dataGridView2_buttonCol(object sender, DataGridViewCellEventArgs e)
    {
            string name = Convert.ToString(dataGridView2.SelectedRows[0].Cells[2].Value);
            ShowRichMessageBox("Code", name);
    }

编辑:

if (e.ColumnIndex != 0) // Change to the index of your button column
            {
                return;
            }
            if (e.RowIndex > -1)
            {
                string name = Convert.ToString(dataGridView2.Rows[e.RowIndex].Cells[2].Value);
                ShowRichMessageBox("Code", name);
            }

如何获取单元格值按钮在数据网格 C# 中单击

传递给 CellClick 事件处理程序的 DataGridViewCellEventArgs 实例具有 ColumnIndex 属性,您可以检查该属性以查看单击是否来自按钮列。

喜欢这个:

private void dgv_buttonCol(object sender, DataGridViewCellEventArgs e)
{
        if (e.ColumnIndex != 4) // Change to the index of your button column
        {
             return;
        }
        if (e.RowIndex > -1)
        {
            string name = Convert.ToString(dgv.Rows[e.RowIndex].Cells[2].Value);
            ShowRichMessageBox("Code", name);
        }
}

对于问题的第二部分,我不确定您的意思,但您当然可以更改行高,也许在 SelectionChanged 事件中使用,或者如果您想更深入地执行操作,请参阅"如何:自定义 Windows 窗体 DataGridView 控件中行的外观"