当前位置: 代码迷 >> .NET组件控件 >> 窗体之间的datagridview控件如何传一整行啊
  详细解决方案

窗体之间的datagridview控件如何传一整行啊

热度:87   发布时间:2016-05-04 23:17:54.0
窗体之间的datagridview控件怎么传一整行啊,
在Form1中有一个datagridview控件,通过数据库获得了数据,我现在想双击某一行后,能够马上在Form2窗体的datagridview控件中显示双击的那行(双击之后马上就能显示出来)。大神来给我解答一下吧。最好写出代码,万分感谢。。。[/size][/b]
------解决思路----------------------
Form1代码
public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
        }
        BindingSource bs = new BindingSource();
        List<Music> list = new List<Music>();
        Form8 frm = null;

        private void button1_Click(object sender, EventArgs e)
        {
            if (frm == null)
            {
                frm = new Form8();
                frm.ParentList = list;
                frm.BindingSource = bs;
            }
            frm.Show(); 
        }

        private void Form7_Load(object sender, EventArgs e)
        {
            bs.DataSource = list;
            this.dataGridView1.DataSource = bs;
        }
    }

    public class Music
    {
        public string Name { get; set; }
        public string Singer { get; set; }
        public string Ablum { get; set; }
    }

form8代码,这里用CellContentDoubleClick有点小问题,你自己调整修改下
public partial class Form8 : Form
    {
        public Form8()
        {
            InitializeComponent();
        }

        public BindingSource BindingSource { get; set; }//这个偷懒了,自己研究下怎么尽可能的减少两边的交互吧

        public List<Music> ParentList { get; set; }

        private static List<Music> sourceList = new List<Music>()
        {
            new Music{ Name="黑色毛衣",Singer="周杰伦",Ablum="十一月的肖邦"},
            new Music{ Name="爱你",Singer="王心凌"}
        };

        private void Form8_Load(object sender, EventArgs e)
        {
            this.dataGridView1.DataSource = sourceList;
        }

        private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.ParentList != null)
            {
                var model = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as Music;
                if (model != null && !this.ParentList.Any(x => x.Name == model.Name))
                {
                    this.ParentList.Add(model);
                    this.BindingSource.ResetBindings(false);
                }
            }
        }
    }
  相关解决方案