繁体   English   中英

从选定的 datagridview 行和哪个事件中获取数据?

[英]Getting data from selected datagridview row and which event?

我在 windows 表单上有一个 DataGridView(Selectionmode:FullRowSelect)和一些文本框,所以我想做的是,每当用户选择一行(可能单击或双击)时,该行的内容必须显示在文本中箱子,

我试过这段代码:

private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show("CEll Double_Click event calls");
    int rowIndex = e.RowIndex;
    DataGridViewRow row = dataGridView1.Rows[rowIndex];
    textBox5.Text = row.Cells[1].Value;
}

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    int rowIndex = e.RowIndex;
    DataGridViewRow row = dataGridView1.Rows[rowIndex];
    textBox5.Text = dataGridView1.Rows[1].Cells[1].Value.ToString();// row.Cells[1].Value;
}

还有许多其他文本框,但主要问题是似乎没有任何事件被触发,我应该使用什么事件来触发,或者是否有我可能设置错误的数据网格属性? 任何帮助,将不胜感激...:(

您可以使用SelectionChanged事件,因为您使用的是FullRowSelect选择模式。 在处理程序内部,您可以访问SelectedRows属性并从中获取数据。 例:

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();
        //...
    }
}

您还可以遍历列集合而不是键入索引...

您可以尝试此点击事件

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();

首先拿一个标签。 将其可见性设置为false,然后在DataGridView_CellClick事件上写入此内容

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

你应该检查你的设计师文件。 打开Form1.Designer.cs和
找到这一行:windows Form Designer生成的代码。
展开这个,你会看到很多代码。 因此,如果没有放置它,请检查datagridview1控件内是否存在此行。

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

我希望它有所帮助。

简单的解决方案如下。 这是来自谷的解决方案的改进。

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);
}

请注意其他读者,上面的代码应该使用FullRowSelect选择模式的datagridview。 如果选择了两行以上,您可以扩展它以给出消息。

您可以使用 SelectionChanged 事件。 CurrentRow.DataBoundItem 将给出绑定项。

SelectionMode 属性应为整行 select。

var item = ([CastToBindedItem])dataGridLocations.CurrentRow.DataBoundItem; tbxEditLocation.Text = item.Name;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM