c# use datatable in other form datagridview
我搜索了很多主题,也在StackOverflow中,但是没有一个解决了我的问题。
这是我的主窗体,我在其中操作数据库并在DataGridView中显示项。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | public partial class Form1 : Form { DatabaseConnection objConnect; string conString; private static DataTable table; DataSet dataSet; public Form1() { InitializeComponent(); CreateConnection(); MakeDataTable(); } public DataTable table { get { return table; } } private void MakeDataTable() { table = new DataTable(); DataColumn column; column = new DataColumn(); column.DataType = Type.GetType("System.String"); column.ColumnName ="Name of Item"; table.Columns.Add(column); etc... } //this connects to my local db through DatabaseConnection.cs //where I got table ItemsInWorld, //from where I take items and add it via InputBox to my datatable table //which works fine and shows all added items private void CreateConnection() { objConnect = new DatabaseConnection(); conString = Properties.Settings.Default.ItemsConnectionString; objConnect.connection_string = conString; objConnect.Sql = Properties.Settings.Default.SQL; dataSet = objConnect.GetConnection; } //I also have here code that show content of this DataTable table in //DataGridView Form1.dataGridView } |
假设我单击Form1中的按钮,那么Form2将与另一个DataGridView一起出现。
在这个表单中,如我所说,我想让另一个DataGridView让我们称之为DataGridV,它将显示与Form1中的DataGridView相同的项,我该怎么做?
这是我的代码,但它只显示空表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | Form2 : form { DataTable table2; DatabaseConnection objConnect; string conString; DataSet dataSet; public DataGridV() { InitializeComponent(); CreateConnection(); CreateDataView(); } private void CreateConnection() { objConnect = new DatabaseConnection(); conString = Properties.Settings.Default.ItemsConnectionString; objConnect.connection_string = conString; objConnect.Sql = Properties.Settings.Default.SQL; dataSet = objConnect.GetConnection; } public void CreateDataView() { Form1 f = new Form1(); table2 = f.TableBackpack; dataGridViewMix.DataSource = new DataView(tableBackpack); } } |
如果
1 | private Form2 form2 = new Form2(); |
然后,在
1 2 3 4 5 | public void SetTable(DataTable table) { table2 = table; // Your code to fill DGV source with table2 } |
在
1 2 | form2.SetTable(this.table); form2.ShowDialog(); |