简体   繁体   中英

Value of Selected dataGridView cell in Textbox

i have a datagridview and textbox in windows form,when i click on a cell of the datagridview the value must copy to the textbox.

I am getting a error:

System.Windows.Forms.DataGridCell Does not contain a definition for RowIndex

I have tried this code

void dataGridView1_Click(object sender, EventArgs e)
 {
      Txt_GangApproved.Text=dataGridView1.CurrentCell.RowIndex.Cells["NO_OF_GANGS_RQRD"].Value.ToString();
 }
foreach (DataGridViewRow RW in dataGridView1.SelectedRows) {
    //Send the first cell value into textbox'
    Txt_GangApproved.Text = RW.Cells(0).Value.ToString;
}

尝试这个-

Txt_GangApproved.Text = dataGridView1.SelectedRows[0].Cells["NO_OF_GANGS_RQRD"].Value.ToString();

You are using wrong event to achieve what you want. Instead of using Click event use CellClick event of dataGridView1 and try the below code:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if(e.RowIndex >= 0 && e.ColumnIndex >= 0)  //to disable the row and column headers
    {
       Txt_GangApproved.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
    }
}

I use the SelectionChanged event sometimes when my DataGridView has its Selection mode to FullRowSelect. Then we can write a line inside the event like:

Txt_GangApproved.Text = Convert.ToString(dataGridView1.CurrentRow.Cells["NO_OF_GANGS_RQRD"].Value);
private void dataGRidView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
            string text = row.Cells[dataGridView1.CurrentCell.ColumnIndex].Value.ToString();
        }
    }

This is 100% working code (using -CellClick- event handler):

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        textBox1.Text = dataGridView1.CurrentCell.Value.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