C#-如何通过单击按钮将数据从dataGridView1传递到另一个? [英] C# - How to pass the data from dataGridView1 to another using a button click?

查看:173
本文介绍了C#-如何通过单击按钮将数据从dataGridView1传递到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以一种形式拥有dataGridView1dataGridView2ButtonAdd.

I have a dataGridView1, dataGridView2 and a ButtonAdd in one Form.

用户将:

1-选择任何一个单元格"或整个行".

1- select any one "Cell" or the "entire Row".

2-选择多个行

然后:

单击按钮后,所选数据将从dataGridView1移到dataGridView2.这就是我要做的全部.

the data selected will be moved from dataGridView1 to dataGridView2 when the button clicked. that's all what i need to do.

我的尝试:

经过多次搜索,我已经尝试过此解决方案,并且几乎可以解决,但是有一个我无法处理的小问题:

I have tried this solution after many searches and it's almost done but there's a little problem I couldn't handle:

完整代码:

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

允许调试:

只需注意一件事,然后再开始:

just Note a one thing before starting:

  • 在所有情况下,删除行(多行或单行)的方法都可以正常工作.
  • 添加到DGV2的方法是问题所在,我从此处提取了它……效果很好选择单行而不是多行时.
  • the method for deleting rows (multi or single) is working fine in all cases.
  • the method for adding to the DGV2 is the problem, I had taken it from here ...it works fine when selecting a single row but not multiple.

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

1- if you have selected a one cell/row it will be added and removed successfully.

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

2- if you have selected a multiple rows lets say the first and the second it will add the second and the third, then definitely will deleted them, but only one is added.. why?!

因为在这里

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

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

gets the current index of the existing rows in the DGV1 and iterate to the number of the selecting rows and add them to DGV2.

截屏:

该过程如何完成的图像: .

image of how the process is done: .

我需要做什么:

应该怎么做才能解决这个问题?

What should be done to solve this problem?

推荐答案

尽管marco有一点,但作为引发异常的原因,该行的所有权归表所有.要绕过此操作,您可能需要这样做...

Although marco has a point, ownership of the row is to the table as exception thrown. To bypass this, you might want to do this way...

//根据您要创建的表创建一个新行 //插入具有相同结构的INTO

// creates a new row based on the table you are about to // insert INTO with same structure

var copyRow = table.NewRow(); 
copyRow.ItemArray = currentRow.ItemArray;
table.Rows.Add( copyRow );

ItemArray是表的所有列属性的列表,其顺序不明确引用Row ["someColumn"].因此,将数组复制到新行将获得所有列.如果两个表的结构都相同,这就是您所提供的方案中的结果.

The ItemArray is a list of ALL the column properties of the table in order without explicit reference to Row["someColumn"]. So copying the array to the new row gets you all the columns. This is - provided both table structures are the same - and appears to be from your scenario provided.

澄清

Clarification

上面的代码只做一行,并且会根据您的循环应用

The above code only does a single row and would be applied based on your loop where the

if (oneCell.Selected)

每行选择了多列,从而使循环有些混乱.实际上,您多次击中同一行.无论如何,我发现您实际上是在Windows应用程序而不是WPF中执行此操作.

You have multiple columns selected per row thus causing some confusion to your loops. You are actually hitting the same row multiple times. In any event, i found you are actually doing this in a Windows Application, not WPF.. I have created a form and posting the code below.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        loadDataIntoGridView1();
    }

    public DataTable tblFrom { get; set; }
    public DataTable tblTo { get; set; }
    private void loadDataIntoGridView1()
    {
        tblFrom = new DataTable();
        tblFrom.Columns.Add("Col1", typeof(string));
        tblFrom.Columns.Add("Col2", typeof(string));

        tblTo = tblFrom.Clone();

        DataRow tmp;
        while (tblFrom.Rows.Count < 20)
        {
            tmp = tblFrom.NewRow();
            tmp["Col1"] = "my row " + tblFrom.Rows.Count;
            tmp["Col2"] = "testing";
            tblFrom.Rows.Add(tmp);
        } 

        dataGridView1.AutoGenerateColumns = true;
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        dataGridView2.AutoGenerateColumns = true;
        dataGridView2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        dataGridView1.DataSource = tblFrom;
        dataGridView2.DataSource = tblTo;
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        // if no ROWS selected, get out.
        if (dataGridView1.SelectedRows.Count == 0)
            return;

        foreach( DataGridViewRow vr in dataGridView1.SelectedRows)
        {
            var currentRow = ((DataRowView)vr.DataBoundItem).Row;
            ((DataTable)dataGridView2.DataSource).ImportRow(currentRow);

            //this will remove the rows you have selected from dataGridView1
            dataGridView1.Rows.RemoveAt(vr.Index);
        }
    }
}

在这里,我有一个表格,其中包含两个与您所拥有的网格相似的表格,以及一个用于移动"记录(但仅一个方向)的按钮,您将不得不针对一个/全部/从/向方向进行调整.

Here, I have a form with the two grids similar to what you had and a single button to "Move" the records (but only one direction), you will have to adjust for one / all / from / to directions.

一些更改.我将网格更改为强制将选择模式应用于整个ROW.这将仅因为您有多个列就可以防止为单个行输入多个条目.仍然可以通过在单元格之间拖动或按Ctrl +单击单个行来进行多选.这样可以选择不在同一可见屏幕区域内的行.

A few changes. I changed the grid to force selection mode to the entire ROW. This will prevent multiple entries for a single row just because you have multiple columns available. Multi-selection is still possible by dragging between cells OR Ctrl+Click on individual rows. This allows for selecting rows not within the same viewable screen region.

我也只是创建了一个create table来强制模拟20行数据,以强制并非同时显示所有行.

I also just did a create table to force simulating 20 rows of data to force not all rows visible at the same time.

单击事件的下一个事件...如果未选择ROWS,请出去...如果存在,请循环遍历,但是这样做是每行一次,而不是如果有多列,则是多次.获取绑定数据行,导入并删除...

Next the click event... If no ROWS selected, get out... If there ARE, cycle through, but this does ONE PER ROW instead of multiple times if multiple columns. Get the binding data row, import and remove...

您本来就很亲密,不需要复制数组.我认为总体问题是您的列模式选择多次击中同一条记录.在第一个单元格的第0行删除后,第1行成为第0行,因此将其复制并删除,由于只有一个记录需要处理,因此您现在不在列表中.在这里,无论选择的是哪一列,我们都将获得整行一次.

You were very close otherwise and did not need the copy-array. I think the overall problem was that of your columns mode selection hitting the same record multiple times. After the remove-at of row 0 for the first cell, row 1 became row 0 and thus copied that, removed and you are now out of a list as there is only one record left to process. Here, we are getting the entire row ONCE, regardless of the column within it selected.

这篇关于C#-如何通过单击按钮将数据从dataGridView1传递到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆