简体   繁体   English

如何对Button进行编程以添加带有值的DataGrid行?

[英]How to program Button to add DataGrid row with values?

My program has an email field, a password field, and a DataGridView to the right. 我的程序在右侧有一个电子邮件字段,一个密码字段和一个DataGridView。 There is a submit button as well. 还有一个提交按钮。 The submit button edits the preset row in the DataGridView but if clicked twice will just re-edit the contents of the first row. 提交按钮可编辑DataGridView中的预设行,但是如果单击两次,将仅重新编辑第一行的内容。

dataGridView1.Rows[0].Cells[0].Value = txtEmail.Text;
dataGridView1.Rows[0].Cells[1].Value = txtPass.Text;

I'm wondering how I can program the button to add a NEW row with the value of txtEmail and txtPass . 我想知道如何对按钮进行编程以添加具有txtEmailtxtPass值的NEW行。 Is there a set method to adding rows via button? 是否有通过按钮添加行的设置方法? And once that is done how would I edit the most recently added row? 完成后,如何编辑最近添加的行? This will present a new row with the new email and new pass every time data is submitted? 每次提交数据时,这将在新行中显示新的电子邮件和新的通行证吗?

Any thoughts? 有什么想法吗?

Assuming your DataGridView has only two columns, and that it's DataSource property is not bound to some collection or a DataTable , this should work: 假设您的DataGridView只有两列,并且它的DataSource属性未绑定到某个集合或DataTable ,这应该可以工作:

private void btnAddInputToGrid_Click(object sender, EventArgs e)
{
    // add the new row, get its index
    var newIndex = dataGridView1.Rows.Add(txtEmail.Text, txtPass.Text);

    // select just the new row
    dataGridView1.ClearSelection();
    dataGridView1.Rows[newIndex].Selected = true;

    // select the cell you're interested in and put it in edit mode
    dataGridView1.CurrentCell = dataGridView1.Rows[newIndex].Cells[0];
    dataGridView1.BeginEdit(false);
}

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

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