如何通过单击按钮将选定的gridview值显示到文本框中 [英] Howdo I display selected gridview value into textbox by clicking button

查看:99
本文介绍了如何通过单击按钮将选定的gridview值显示到文本框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个datagridview,其中包含来自excel文件的一些数据。

我希望能够使用我单击按钮时当前选择的单元格填充文本框。

我尝试过以下方法,但未找到方法做到这一点。

 private void btnGetValue_Click(object sender,EventArgs e)
{

txtField1.Text = dataGridView1.Rows [e.RowIndex] .Cells [e.ColumnIndex] .Value.ToString();
}





我尝试过:



txtField1.Text = dataGridView1.Rows [e.RowIndex] .Cells [e.ColumnIndex] .Value.ToString();

解决方案

如果您只使用单一选择,请确保在DataGridView上设置模式:

 dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect; 



现在,您可以使用 dataGridView 控件的 SelectedCells 属性:

  private   void  btnGetValue_Click(< span class =code-keyword> object  sender,System.EventArgs e)
{
var selectedcell = dataGridView1.SelectedCells ?。计数== 1
? dataGridView1.SelectedCells [ 0 ]
null ;

if (selectedcell!= null
{
// 对所选单元格执行某些操作...
}
}


I have a datagridview that gets populated with some data from an excel file.
I want to be able to populate a textbox with the cell that I have currently selected when I click the button.
I have tried the following but have been unsuccessful in finding a way to do this.

private void btnGetValue_Click(object sender, EventArgs e)
       {

           txtField1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
       }



What I have tried:

txtField1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();

解决方案

If you are only working with single selection make sure that you set the mode on the DataGridView:

dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;


Now, you can work with the SelectedCells property of the dataGridView control:

private void btnGetValue_Click(object sender, System.EventArgs e)
{
    var selectedcell = dataGridView1.SelectedCells?.Count == 1
                           ? dataGridView1.SelectedCells[0]
                           : null;

    if (selectedcell != null)
    {
        // do something with the selected cell...
    }
}


这篇关于如何通过单击按钮将选定的gridview值显示到文本框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆