C# - 如何使用单击按钮将数据从dataGridView1传递到另一个?

时间:2017-11-23 11:18:30

标签: c# datagridview datagrid datagridviewcolumn datagridviewrow

我在一个表单中有dataGridView1dataGridView2ButtonAdd

用户将:

1-选择任何一个" Cell"或者整个行"。

2 - 选择多行

然后:

单击按钮时,所选数据将从dataGridView1移动到dataGridView2。这就是我需要做的所有事情。

我的尝试:

我经过多次搜索后尝试了这个解决方案,但差不多已经完成了,但是我无法解决这个问题:

完整代码:

private const string strconneciton = @"YourConnectionString";
    SqlConnection con = new SqlConnection(strconneciton);
    SqlCommand cmd = new SqlCommand();
    DataTable dataTable;

private void loadDataIntoGridView1()
    {
        try
        {
            con.Open();
            cmd.CommandText = "SELECT id, accNum, accName FROM Employees";
            cmd.Connection = con;

            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = cmd;

            dataTable = new DataTable();
            adapter.Fill(dataTable);

            BindingSource bSource = new BindingSource();
            bSource.DataSource = dataTable;
            dataGridView1.DataSource = bSource;

            //i don't know if this line is useful...
            dataGridView2.DataSource = dataTable.Clone();

            adapter.Update(dataTable);
            con.Close();

        }
        catch (Exception ed)
        {
            con.Close();
            MessageBox.Show(ed.Message);
        }
    }//end loadDataIntoGridView1


private void buttonSend_Click(object sender, EventArgs e)
{       
    if (dataGridView1.SelectedCells.Count > 0)
    {
        foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
        {
            if (oneCell.Selected)
            {
                //this should add the rows that is selected from dataGridView1 and,
                //pass it to dataGridView2
                var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
                 ((DataTable)dataGridView2.DataSource).ImportRow(currentRow);

                //this will remove the rows you have selected from dataGridView1
                dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
            }//end if
        }//end foreach
    }//end if
}//end button click

让我们调试:

只需注意开始之前的一件事:

  • 删除行(多个或单个)的方法在所有情况下都正常工作。
  • 添加到DGV2的方法是问题,我从here获取了它......当选择单行而不是多行时它可以正常工作。

1-如果您选择了一个单元格/行,则会成功添加和删除它。

2-如果您选择了多行,请说第一个和第二个它将添加第二个和第三个,然后肯定会删除它们,但只添加一个.. 为什么?!

因为这里

var currentRow = ((DataRowView)dataGridView1.CurrentRow.DataBoundItem).Row;
            ((DataTable)dataGridView2.DataSource).ImportRow(currentRow);   

获取DGV1中现有行的当前索引,并迭代到选择行的数量并将它们添加到DGV2。

截图:

过程如何完成的图像: image of how the process is done

我需要做什么: what i need to do

应该怎样解决这个问题?

2 个答案:

答案 0 :(得分:0)

而不是

ImportRow(currentRow)

使用类似的东西:

table.Rows.Add(currentRow);

让我知道这是否有效!

答案 1 :(得分:0)

这是一个完整的代码片段。 在此示例中,我使用2 BindingList来满足您的要求。用户点击该按钮后,该示例会将所选项目从dgv1data复制到dgv2data。然后它会从dgv1data中删除项目。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

namespace MoveDataBetweenDataGridView_47454256
{
    public partial class Form1 : Form
    {
        static BindingList<dgventry> dgv1data = new BindingList<dgventry>();
        static BindingList<dgventry> dgv2data = new BindingList<dgventry>();
        DataGridView dgv1 = new DataGridView();
        DataGridView dgv2 = new DataGridView();
        Button btn = new Button();

        public Form1()
        {
            InitializeComponent();

            InitOurStuff();
            for (int i = 0; i < 10; i++)
            {
                dgv1data.Add(new MoveDataBetweenDataGridView_47454256.dgventry
                {
                    col1 = $"col1_{i}", col2 = $"col2_{i}", col3 = $"col3_{i}"});
                }

        }

        private void InitOurStuff()
        {
            this.Controls.Add(dgv1);//add the DGV to the form
            dgv1.DataSource = dgv1data;//bind our data to it
            dgv1.Dock = DockStyle.Left;//place the DGV somewhere on the form

            this.Controls.Add(dgv2);//add the DGV to the form
            dgv2.DataSource = dgv2data;//bind out data to it
            dgv2.Dock = DockStyle.Right;//place the DGV somewhere on the form

            this.Controls.Add(btn);//add the Button to the form
            btn.Dock = DockStyle.Bottom;//place the Button somewhere on the form
            btn.Click += Btn_Click;//give the Button a event handler
        }




        private void Btn_Click(object sender, EventArgs e)
        {
            List<int> doneIndices = new List<int>();//this will keep track of the row indices we have dealt with

            if (dgv1.SelectedCells.Count > 0)//if something is selected
            {
                foreach (DataGridViewCell item in dgv1.SelectedCells)//loop through the selected cells
                {
                    if (!doneIndices.Contains(item.OwningRow.Index))//if this cell does not belong to a row index we already processed
                    {
                        //we haven't done this row yet
                        dgv2data.Add((dgventry)item.OwningRow.DataBoundItem);//add the DataBoundItem to the other DGV data
                        doneIndices.Add(item.OwningRow.Index);//put the current row index in our tracking list
                    }
                    else
                    {
                        //we have done this row already, move on to the next one
                        continue;
                    }
                }
            }

            //remove all the duplicate entries
            foreach (dgventry item in dgv2data)
            {
                dgv1data.Remove(item);
            }
        }
    }



    public class dgventry
    {
        public string col1 { get; set; }
        public string col2 { get; set; }
        public string col3 { get; set; }

    }
}