简体   繁体   中英

C# - Selecting a Column in a DataGridView

I am creating a football roster using C# and Visual Studio. I've created a DataGridView calling dgvPlayer.

DGV

My goal is to select a box on dgvPlayer and have the information be copied into a Name textbox, Team textbox, etc. I'm really just confused as to the how to identify that a certain box is being selected. Please help!

dgvPlayer.Columns["Name"].DefaultCellStyle.Format

Based on what you are trying to do, you will have to add a handler for the CellClick event. The event will fire everytime the user make a click on some cell, then you will have to put your own business logic there. You can do something like this:

dgvPlayer.CellClick += dgvPlayer_CellClick;

private void dgvPlayer_CellClick(object sender, DataGridViewCellEventArgs e)
{
     yourTextBox.Text = dgvPlayer.Rows[e.RowIndex].Cells[e.ColumnIndex].ToString();
}

Something like this that adds some validation against selecting the header row of the grid view

private void dgvPlayer_CellClick(object sender, DataGridViewCellEventArgs e)
{
        if (e.RowIndex != -1)
        {
            txtTextBox.Text = dgvPlayer.Rows[e.RowIndex].Cells[e.ColumnIndex].ToString();          
        }
}

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