Getting data from selected datagridview row and which event?

后端 未结 5 1354
眼角桃花
眼角桃花 2020-12-08 06:53

I have a DataGridView (Selectionmode: FullRowSelect) on a windows form along with some textboxes, so what i want to do is that whenever a user selects a row(click or double_

相关标签:
5条回答
  • 2020-12-08 07:08

    You can try this click event

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0)
        {
            DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
            Eid_txt.Text = row.Cells["Employee ID"].Value.ToString();
            Name_txt.Text = row.Cells["First Name"].Value.ToString();
            Surname_txt.Text = row.Cells["Last Name"].Value.ToString();
    
    0 讨论(0)
  • 2020-12-08 07:17

    Simple solution would be as below. This is improvement of solution from vale.

    private void dgMapTable_SelectionChanged(object sender, EventArgs e) 
    {
        int active_map=0;
        if(dgMapTable.SelectedRows.Count>0)
            active_map = dgMapTable.SelectedRows[0].Index;
        // User code if required Process_ROW(active_map);
    }
    

    Note for other reader, for above code to work FullRowSelect selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.

    0 讨论(0)
  • 2020-12-08 07:19

    First take a label. set its visibility to false, then on the DataGridView_CellClick event write this

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
        // then perform your select statement according to that label.
    }
    //try it it might work for you
    
    0 讨论(0)
  • 2020-12-08 07:20

    You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:

    private void dataGridView_SelectionChanged(object sender, EventArgs e) 
    {
        foreach (DataGridViewRow row in dataGridView.SelectedRows) 
        {
            string value1 = row.Cells[0].Value.ToString();
            string value2 = row.Cells[1].Value.ToString();
            //...
        }
    }
    

    You can also walk through the column collection instead of typing indexes...

    0 讨论(0)
  • 2020-12-08 07:21

    You should check your designer file. Open Form1.Designer.cs and
    find this line: windows Form Designer Generated Code.
    Expand this and you will see a lot of code. So check Whether this line is there inside datagridview1 controls if not place it.

    this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); 
    

    I hope it helps.

    0 讨论(0)
提交回复
热议问题