简体   繁体   中英

Selecting value in datagrid using KeyUp event

i want to display the selected value in datagridview to textfields by using KeyUp and KeyDown events

private void gridView_KeyUp(object sender, KeyEventArgs e)
{
    try
    {
        //if (e.RowIndex >= 0)
        if(e.KeyCode == Keys.Up)
        {
            DataGridViewRow row = this.gridView.Rows[e.KeyCode];

            txtboxStudentNum.Text = row.Cells["ID_Number"].Value.ToString();
            txtboxName.Text = row.Cells["Name"].Value.ToString();
            comboCourse.SelectedItem = row.Cells["Course"].Value.ToString();
            EPCdisplay.Text = row.Cells["EPCNumber"].Value.ToString();
            txtboxSerialNum.Text = row.Cells["SerialNumber"].Value.ToString();
            txtboxModelNum.Text = row.Cells["ModelNumber"].Value.ToString();
            comboCategory.SelectedItem = row.Cells["Category"].Value.ToString();
            comboYrLevel.SelectedItem = row.Cells["Level"].Value.ToString();
            txtboxEquipDesc.Text = row.Cells["EquipDesc"].Value.ToString();
            comboSem.Text = row.Cells["Semester"].Value.ToString();


            AddDatabase get_image = new AddDatabase();
            get_image.ID = txtboxStudentNum.Text;
            get_image.getimage();


        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
} 

if you are looking to get the Value of Selected Cell then All you Need to is trigger the DataGridView KeyDown Event and write the code as

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            txtName.Text = dataGridView1.CurrentCell.Value.ToString();
            //do whatever you want to
        }
    }

and if you want to get the whole row and perform operations, you can do it as

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            txtID.Text = dataGridView1.Rows[row].Cells[0].Value.ToString();
            txtName.Text = dataGridView1.Rows[row].Cells[1].Value.ToString();
            //do whatever you want to
        }
    }

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