将选定的行从一个gridview添加到另一个 [英] add selected row from one gridview to another
问题描述
我有2个 GridView
控件。我需要将选定的行从一个GridView添加到另一个GridView。 (我直接单击GridView从GridView中选择行。)
I have 2 GridView
controls. I need to add the selected row from one GridView to a second GridView. (I select row from GridView by clicking direct to GridView.)
这是我的代码,但是它将所有数据从gridview1复制到gridview2。我只需要选择的行。
Here's my code, but it copies all data from gridview1 to gridview2. I need the selected row only.
private void button6_Click(object sender, EventArgs e)
{
DataGridViewColumn newCol = null;
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
newCol = new DataGridViewColumn(col.CellTemplate);
newCol.HeaderText = col.HeaderText;
newCol.Name = col.Name;
dataGridView2.Columns.Add(newCol);
}
dataGridView2.RowCount = dataGridView1.RowCount;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
dataGridView2.Rows[row.Index].Cells[col.Name].Value = row.Cells[col.Name].Value;
}
}
我填充了 dataGridView1
与数据表:
SqlConnection con = new SqlConnection(@"Data Source=AFZAL\SQLEXPRESS;Initial Catalog=GIMS_LabInfo;Integrated Security=True");
con.Open();
SqlCommand sc = new SqlCommand("SELECT PROFCODE,PROFNAME FROM PROFNAMES$ WHERE (PROFNAME LIKE '" + textBox1.Text + "%') AND PROFCODE NOT IN (SELECT PROFCODE FROM MAP) ORDER BY Profname desc ", con);
sc.ExecuteNonQuery();
SqlDataAdapter sda = new SqlDataAdapter(sc);
DataTable data = new DataTable();
sda.Fill(data);
dataGridView1.DataSource = data;
推荐答案
设置 dataGridView1之后立即。数据源
:
dataGridView1.DataSource = yourDataTable;
设置 dataGridView2.DataSource
克隆结构 DataTable
(例如列):
Set dataGridView2.DataSource
to clone the structure (such as Columns) of the first DataTable
:
dataGridView2.DataSource = yourDataTable.Clone();
或:
dataGridView2.DataSource = ((DataTable)dataGridView1.DataSource).Clone();
然后在您的按钮单击事件中,您所需要做的就是:
Then in your button click event, all you need is this:
private void button6_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
return;
var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
((DataTable)dataGridView2.DataSource).ImportRow(currentRow);
}
如何为每次点击添加多行?现在,当我选择第二行时,它将替换dataGridView2中的第一行。
How can I add multiple rows on each click? As right now when I select second row, it replaces the First one in dataGridView2.
如果您有多个选择的行,您将必须遍历 SelectedRows
属性。试试这个:
If you have multiple selected rows, you'll have to iterate over the SelectedRows
property. Try this:
private void button1_Click(object sender, EventArgs e)
{
if (dataGridView1.CurrentRow == null)
return;
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
((DataTable)dataGridView2.DataSource).ImportRow(((DataRowView)row.DataBoundItem).Row);
}
这篇关于将选定的行从一个gridview添加到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!