C#中dataGridView控件數據綁定

踏上.NET的路程,菜鳥碰到的第一個問題,mark一下函數

問題:不一樣窗體dataGridView之間的數據傳遞,經過數據綁定實現(假設Form2中的數據要傳遞到Form1中):this

1. 定義一個類,存放dataGridView的數據;spa

2. 在Form2中定義dataGridView數據列表,並將數據存放進去;code

3.From2中定義返回綁定數據的函數,返回綁定數據;orm

4. Form1中初始化Column;blog

5. 在Form1中出發Form2,在結束後將From2返回的綁定數據傳到Form1中的dataGridView中,完成數據傳遞。get

 

From1代碼:string

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 WindowsFormsApplication11
{
    public partial class Form1 : Form
    {
        BindingSource source = new BindingSource();

        public Form1()
        {
            InitializeComponent();
            Column1.DataPropertyName = "_ID";
            Column2.DataPropertyName = "_Name";
            Column3.DataPropertyName = "_Value";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form2 dd = new Form2();
            if (dd.ShowDialog() == DialogResult.OK)
            {
                source.Clear();
                source = dd.returnValue();
                dataGridView1.DataSource = source;
 
            }
        }
    }
}

 

Form2代碼:it

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 WindowsFormsApplication11
{
    public partial class Form2 : Form
    {
        List<DataGrid> dd = new List<DataGrid>();

        

        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            dd.Clear();
            for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
            {
                DataGrid aa = new DataGrid();
                aa._ID = dataGridView1.Rows[i].Cells[0].Value.ToString();
                aa._Name = dataGridView1.Rows[i].Cells[1].Value.ToString();
                aa._Value = dataGridView1.Rows[i].Cells[2].Value.ToString();
                dd.Add(aa);
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        public BindingSource returnValue()
        {
            BindingSource source = new BindingSource();
            source.Clear();
            foreach (DataGrid data in dd)
            {
                source.Add(data);
            }
            return source;
        }

    }
}

 

定義類代碼:io

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication11
{
    class DataGrid
    {
        public string _ID { get; set; }
        public string _Name { get; set; }
        public string _Value { get; set; }
    }

}
相關文章
相關標籤/搜索