我有2个GridView
控件。我需要将选定的行从一个GridView添加到第二个GridView。 (我通过单击“直接连接到GridView”从GridView中选择行。)
这是我的代码,但它将所有数据从gridview1复制到gridview2。我只需要选定的行。
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;
}
}
我使用DataTable填充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;
答案 0 :(得分:0)
设置dataGridView1.DataSource
后立即
dataGridView1.DataSource = yourDataTable;
设置dataGridView2.DataSource
以克隆第一个DataTable
的结构(例如列):
dataGridView2.DataSource = yourDataTable.Clone();
或者:
dataGridView2.DataSource = ((DataTable)dataGridView1.DataSource).Clone();
然后在您的按钮点击事件中,您只需要:
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中的第一行。
如果您有多个选定的行,则必须遍历SelectedRows
属性。试试这个:
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);
}