【问题标题】:C# How do I copy a selected datagridview row's value from one form to a datagridview's row on another form?C#如何将选定的datagridview行值从一个表单复制到另一个表单上的datagridview行?
【发布时间】:2017-07-31 21:15:18
【问题描述】:

我正在使用 html 敏捷包来获取网格视图的数据。我只是想使用列按钮复制一行以将其发送到另一个表单上的空白网格视图。没有数据绑定或 SQL。填充网格后,我无需按下列按钮即可获得整个数据网格视图。我的代码是:

表格 1

private void LeadsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    Database DB = new Database(LeadsDataGridView.DataSource);

    var senderGrid = (DataGridView)sender;

    if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
    {
        DB.Row = LeadsDataGridView.CurrentRow;
    }

    Search_Table.AcceptChanges();

    LeadsDataGridView.DataSource = Search_Table;
}

表格 2

public Database(object DataSource)
{
    InitializeComponent();
    InitDBTable();
    DB_GridView.DataSource = DataSource;
}

【问题讨论】:

  • Using this method should work fine。那个 SO 帖子是关于传递一个字符串,但是,只要你的方法期望你打算传递的参数类型,你就可以传递任何东西。
  • datagridview != wpf datagrid != gridview。你用的是哪一个?
  • 也许这个问题太宽泛了。如果每个列的值只是简单地输入,你将如何将单个 datagridview 行的值复制到另一个 datagridview?

标签: c# winforms datagridview html-agility-pack


【解决方案1】:

这里有一个最小的例子,希望能帮助你。

MainWindow.xaml

<Window x:Class="PassingValuesFromFormToForm_45425412.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PassingValuesFromFormToForm_45425412"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="61,60,0,0" VerticalAlignment="Top" Width="259"/>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="29,13,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Collections.Generic;
using System.Windows;

namespace PassingValuesFromFormToForm_45425412
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<dgvEntry> dgvList = new List<dgvEntry>();
        public MainWindow()
        {
            InitializeComponent();
            dgvList.Add(new PassingValuesFromFormToForm_45425412.dgvEntry { col1 = "blah blah", col2 = "blehbleh" });
            dataGrid.AutoGenerateColumns = true;
            dataGrid.ItemsSource = dgvList;
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            Window1 win1 = new Window1((dgvEntry)dataGrid.Items[0]);
            win1.Show();
        }
    }

    public class dgvEntry {
        public string col1 { get; set; }
        public string col2 { get; set; }
    }
}

Window1.xaml

<Window x:Class="PassingValuesFromFormToForm_45425412.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:PassingValuesFromFormToForm_45425412"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" Margin="23,39,0,0" VerticalAlignment="Top" Width="181"/>

    </Grid>
</Window>

Window1.xaml.cs

using System.Collections.Generic;
using System.Windows;

namespace PassingValuesFromFormToForm_45425412
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        public Window1(dgvEntry incomingItem)
        {
            InitializeComponent();
            dataGrid.AutoGenerateColumns = true;
            dataGrid.ItemsSource = new List<dgvEntry> { incomingItem };
        }
    }
}

这是 WinForms 的更新。 同样,这是一个最小的示例。出于本示例的目的,我在表单设计器中什么也没做。 一切都是通过代码来完成的。

Form1.cs

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {

        DataGridView dgv = new DataGridView();
        BindingList<dgvitem> itemsList = new BindingList<dgvitem>();
        bool SendAsRow = true;//just a variable to trigger the proper method in 'Dgv_CellContentClick'
        Button independantButton = new Button();

        public Form1()
        {
            InitializeComponent();
            InitializeTheDGV();
            AddTheButton();
            itemsList.Add(new dgvitem { JustaTextField = "aksldjf sadfjasifuqw adsfasf" });
            itemsList.Add(new dgvitem { JustaTextField = "qwerioqu aisdfnvmz, oaa"});
        }

        private void InitializeTheDGV()
        {
            dgv.Location = new Point(this.Location.X + 5, this.Location.Y + 5);
            dgv.DataSource = itemsList;
            dgv.AutoGenerateColumns = false;
            this.Controls.Add(dgv);
            dgv.Columns.Add(new DataGridViewTextBoxColumn() { HeaderText = "My col header", Name="mycol1" });
            dgv.Columns.Add(new DataGridViewButtonColumn() { HeaderText = "click in this column", Name = "mycol2" });
            dgv.Columns["mycol1"].DataPropertyName = "JustaTextField";
            dgv.CellContentClick += Dgv_CellContentClick;
        }

        private void Dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!(sender is DataGridView))
            {
                return;
            }

            /*
             * Experiment and Pick your poison
             */
            if (SendAsRow)
            {
                Form2 f2r = new Form2(dgv.Rows[e.RowIndex]);
                f2r.Show();
            }
            else
            {
                Form2 f2 = new Form2((string)dgv.Rows[e.RowIndex].Cells[0].FormattedValue);
                f2.Show();
            }
            /**/
        }


        private void AddTheButton()
        {
            independantButton.Location = new Point(this.Location.X + 5, this.Location.Y + dgv2.Height + 15);
            independantButton.Click += IndependantButton_Click;
            this.Controls.Add(independantButton);
        }

        private void IndependantButton_Click(object sender, System.EventArgs e)
        {
            /*
             * Experiment and Pick your poison
             */
            if (SendAsRow)
            {
                Form2 f2r = new Form2(dgv.SelectedRows[0]);
                f2r.Show();
            }
            else
            {
                Form2 f2 = new Form2((string)dgv.SelectedRows[0].Cells[0].FormattedValue);
                f2.Show();
            }
            /**/

        }
    }


    public class dgvitem
    {
        public string JustaTextField { get; set; }
    }
}

Form2.cs

using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form2 : Form
    {
        DataGridView dgv2 = new DataGridView();
        BindingList<dgv2item> dgv2list = new BindingList<dgv2item>();

        //this is the 'default' constructor which takes no argument
        public Form2()
        {
            InitializeComponent();
            MakeTheGrid();
        }

        //this form constructor takes a String parameter so you can pass only a string
        public Form2(string incomingText)
        {
            InitializeComponent();
            MakeTheGrid();
            dgv2list.Add(new dgv2item { coolBeans = incomingText });//add the incoming String to the itemList, which will in-turn update the DataGridView
        }


        //this form constructor takes a DataGridViewRow parameter so you can pass the whole row
        public Form2(DataGridViewRow incomingRow)
        {
            InitializeComponent();
            MakeTheGrid();
            dgv2list.Add(new dgv2item { coolBeans = (string)incomingRow.Cells[0].FormattedValue});//add the value of the cell you want out of the row to the itemlist, which will in-turn update the DataGridView
        }


        private void MakeTheGrid()
        {
            dgv2.Location = new Point(this.Location.X + 15, this.Location.Y + 15);//it has to go somewhere...
            dgv2.AutoGenerateColumns = true;
            dgv2.DataSource = dgv2list;//define where to find the data
            this.Controls.Add(dgv2);//add it to the form
        }
    }


    public class dgv2item
    {
        public string coolBeans { get; set; }
    }
}

【讨论】:

  • 我喜欢您列出 blaze_125 的示例。但是,它帮助我了解了您认为是我的问题要点背后的逻辑;我的程序代码与您的示例如此不同,以至于我无法理解您的代码中发生了什么。我曾尝试使用: DB_Table.Rows.Add(Search_Table.Rows[e.RowIndex]);作为收集行的一种方式,但是我收到一条错误消息,说“该行已经属于另一个表”我现在正在使用带有 DataSource 的 DataTable。我将继续做一些研究并尝试找到解决方案。如果我遇到什么,我会在这里发布。
  • 请在您的开篇文章中跟进@ASh 问题。标签和您帖子的内容有些矛盾。我给了您一个 WPF 示例,但是感觉您实际上可能正在使用表单而不是 WPF。如果您确实在使用表单,我会写另一个答案。若要了解您是否使用 WPF,请查看 Visual Studio 中的解决方案资源管理器。如果您的解决方案资源管理器列出了“.xaml”文件,那么您在 WPF 项目中。如果您没有列出该文件扩展名,那么您可能正在使用 Forms。
  • 你是对的 blaze_125,我为误会道歉。我使用了不正确的标签。你现在的代码实际上对我来说更有意义。为了回答 Ash 的问题,我在 DataPile 类中使用了带有 DataTable 和“get”“set”变量的 DataGridView。运行条件搜索后,我正在 DGV 中生成数据。复制按钮在 DGV 中作为一列。我有一个单独的按钮来打开表单。我使用 FullRowSelect 作为选择模式。
  • 感谢您解决这个问题。我用可以帮助您理解手头任务的代码更新了我的答案。
  • +1 感谢 blaze_125。这正是我想要获得的代码和逻辑。原来我错过了 BindingList DB_GridViewList = new BindingList();你刚刚在这个期限内救了我的命。我是业务应用程序世界的新手。从我的名字可以看出,我主要涉足使用 java 或 LUA 的游戏插件。有时我会将 c# 与 Unity 一起使用,再次非常感谢。干杯!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多