linguini
linguini

Reputation: 1939

How to get a cell value buttonclick in DataGrid C#

I want to display a particular cell value a row in a ShowRichMessageBox when i click on the button but this event display the cell value if click anywhere on the row....!

what is wrong here.....How can I fix the above problem???

I have some logvalues which are big but it's already loaded in the cell so, 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);

    }

Edit:

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

Upvotes: 0

Views: 7832

Answers (1)

stuartd
stuartd

Reputation: 73313

The DataGridViewCellEventArgs instance passed to the CellClick event handler has a ColumnIndex property, which you can check to see if the click came from the button column.

Like this:

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

For the second part of your question, I'm not sure what you mean but you could certainly change the row height, perhaps using in the SelectionChanged event, or if you want to do something more in depth see "How to: Customize the Appearance of Rows in the Windows Forms DataGridView Control"

Upvotes: 3

Related Questions