简体   繁体   English

将单选行从datagridview复制到另一个datagridview

[英]Copying A SINGLE SELECTED row from a datagridview to another datagridview

what i need to do : 1. When a user clicks on A ROW of a datagriview. 我需要做的是:1.当用户单击datagriview的ROW时。 Only this row is displayed in another datagridview (so that it can be edited etc...) 仅此行显示在另一个datagridview中(以便可以对其进行编辑等)。

NOTE : grid_display = from where i need to get the row. 注意:grid_display =我需要从哪里获取行。 NOTE : grid_detail = to where i need the single row to be copied. 注意:grid_detail =到我需要将单行复制到的位置。

what i have till now: 我到目前为止所拥有的:

   foreach (DataGridViewColumn c in grid_display.Columns)
            {
                grid_detail.Columns.Add(c.Clone() as DataGridViewColumn);
            }

            //then you can copy the rows values one by one (working on the selectedrows collection)
            foreach (DataGridViewRow r in grid_display.SelectedRows)
            {
                int index = grid_detail.Rows.Add(r.Clone() as DataGridViewRow);
                foreach (DataGridViewCell o in r.Cells)
                {
                    grid_detail.Rows[index].Cells[o.ColumnIndex].Value = o.Value;
                }
            }

            }

I am only able to make a new row. 我只能进行新的一行。 But not to feed in the selected row in it. 但不要输入其中的选定行。 Any help ? 有什么帮助吗?

As I mentioned in my comment already, you should use a DataSource for your DataGridView s and use a DataGridView as view only. 正如我在评论中已经提到的那样,您应该为DataGridView使用DataSource ,并且仅将DataGridView用作视图。

Here you have complete example that demonstrates how to use a DataTable as a DataSource for a DataGridView and move a DataRow between them. 在这里,您有一个完整的示例,演示了如何使用DataTable作为DataGridViewDataSource以及如何在它们之间移动DataRow

  1. Creata a new windows forms project and copy paste the code. 创建一个新的Windows窗体项目并复制粘贴代码。
  2. Click on a row, by clicking left from the row (indicated with a small arrow > ) in the DataGridView 单击一行,方法是在DataGridView从该行的左侧单击(用小箭头>指示)。
  3. Click on the Button below the DataGridView to move the selected DataRow to the other DataGridView 单击DataGridView下面的Button ,将选定的DataRow移动到另一个DataGridView

NOTE 1: All the controls are crated in Form1_Load so dont bother drag dropping controls on the form. 注意1:所有控件都在Form1_Load中创建,因此不必费心在窗体上拖放控件。

NOTE 2: If you have only a column selected, no rows will be moved. 注意2:如果仅选择一列,则不会移动任何行。 You have to select the entire row. 您必须选择整行。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load +=Form1_Load;
        }

        public DataGridView ViewA, ViewB;

        public DataTable DataA, DataB;

        public Button MoveSelectedFromViewAToB, MoveSelectedFromViewBToA;

        private void Form1_Load(object sender, EventArgs e)
        {
            //Create two DataGridViews on the form
            ViewA = new DataGridView()
            {
                Location = new Point(0, 0),
                Size = new Size(300, 100),
                MultiSelect = false
            };

            ViewB = new DataGridView()
            {
                Location = new Point(300, 0),
                Size = new Size(300, 100),
                MultiSelect = false
            };
            this.Controls.Add(ViewA);
            this.Controls.Add(ViewB);

            //Add Two buttons
            Button MoveSelectedFromViewAToB = new Button()
            {
                Text = "A => B",
                Location = new Point(10, 120),
            };
            MoveSelectedFromViewAToB.Click += MoveSelectedFromViewAToB_Click;
            MoveSelectedFromViewBToA = new Button()
            {
                Text = "A <= B",
                Location = new Point(310, 120)
            };
            MoveSelectedFromViewBToA.Click += MoveSelectedFromViewBToA_Click;
            this.Controls.Add(MoveSelectedFromViewAToB);
            this.Controls.Add(MoveSelectedFromViewBToA);

            //Make sure the form has appropriate size
            this.Size = new Size(600, 200);

            //Create a DataTable and add some data
            DataA = new DataTable();
            DataA.Columns.Add("Key", typeof(System.String));
            DataA.Columns.Add("Value", typeof(System.String));
            DataA.Rows.Add(new object[] { "KeyA", "ValueA" });
            DataA.Rows.Add(new object[] { "KeyB", "ValueB" });
            DataA.Rows.Add(new object[] { "KeyC", "ValueC" });
            DataA.Rows.Add(new object[] { "KeyD", "ValueD" });

            //Make sure DataB has the same layout as DataA
            DataB = DataA.Clone();

            //Assign both datatables to the views
            ViewA.DataSource = new BindingSource() { DataSource = DataA };
            ViewB.DataSource = new BindingSource() { DataSource = DataB };
        }

        /// <summary>
        /// Moves rows from view A to B
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MoveSelectedFromViewAToB_Click(object sender, EventArgs e)
        {
            if (ViewA.SelectedRows.Count == 0 || DataA.Rows.Count == 0 || ViewA.SelectedRows[0].Index > DataA.Rows.Count -1) return;//No row selected, or data table is empty
            DataB.ImportRow(DataA.Rows[ViewA.SelectedRows[0].Index]);
            DataA.Rows.RemoveAt(ViewA.SelectedRows[0].Index);
        }

        /// <summary>
        /// Moves rows from view B to A
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MoveSelectedFromViewBToA_Click(object sender, EventArgs e)
        {
            if (ViewB.SelectedRows.Count == 0 || DataB.Rows.Count == 0 || ViewB.SelectedRows[0].Index > DataB.Rows.Count -1) return; //No row selected, or data table is empty
            DataA.ImportRow(DataB.Rows[ViewB.SelectedRows[0].Index]);
            DataB.Rows.RemoveAt(ViewB.SelectedRows[0].Index);
        }
    }
}

With this you should be able to implement your logic of when to move a row to your grid_detail and when to move it back to grid_display . 有了这个,您应该能够实现何时将行移到grid_detail以及何时将其移回到grid_display

Guys i got to solve the problem. 伙计们,我必须解决这个问题。 I proceeded as below. 我进行如下操作。

First i cloned the columns, for this i created a method 首先我克隆了列,为此我创建了一个方法

  public void change_header()
        {
            DisplayDataGrid();
            grid_detail.Columns.Clear();

            foreach (DataGridViewColumn c in grid_display.Columns)
            {
                grid_detail.Columns.Add(c.Clone() as DataGridViewColumn);
            }
        }

then I copied the SELECTED row only and displayed it in the second datagridview (as header columns have already been duplicated) the data now displayed are presentable. 然后我仅复制了SELECTED行,并将其显示在第二个datagridview中(因为标题列已经被复制),现在显示的数据是可显示的。

How I copied selected row ? 我如何复制选定的行? Here it is. 这里是。

 grid_detail.Rows.Clear(); 
            DataRow[] dRows = new DataRow[grid_display.SelectedRows.Count];
            for (int i = 0; i < grid_display.SelectedRows.Count; i++)
                dRows[i] = ((DataRowView)grid_display.SelectedRows[i].DataBoundItem).Row;
                foreach (DataRow dgvRow in dRows)
                {
                    grid_detail.Rows.Insert(0, dgvRow.ItemArray);
                }
                grid_detail.Refresh();

Where grid_display is dgv with FULL data and grid_detail is the dgv with the selected row only. 其中grid_display是具有完整数据的dgv,而grid_detail是仅具有选定行的dgv。 Thanks. 谢谢。

If the data your grid_display comes from a query (like MySQL, etc.), what you can do is to redo the query but make it specific so that the resulting data is the same as the one you selected when you clicked the cell from grid_display...then put the result in your grid_detail. 如果grid_display的数据来自查询(例如MySQL等),则可以做的是重做查询,但要使其具体化,以使结果数据与单击grid_display单元格时选择的数据相同。 ...然后将结果放入您的grid_detail中。

This is one solution I think you could do...but you cannot do multiple transfer at once because you are making a query... 我认为这是一个解决方案,您可以...但是您不能一次执行多次传输,因为您正在查询...

Hope it helps... :D 希望对您有帮助...:D

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

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