搜索了许多主题,也在stackoverflow中,但是没有一个可以解决我的问题
这是我的主要窗体,我在其中操作数据库并在数据网格视图中显示项目
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 相同的项目,我该怎么办?
这是我的代码,但它只显示空表
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);
}
}
如果Form1
负责打开 Form2
的实例,那么Form1
应该将此实例保存在私有字段中:
private Form2 form2 = new Form2();
然后,在 Form2
中创建一个公共方法,该方法将允许Form1
设置表字段(而不是Form2
尝试从代码示例中将其从Form1
中提取
public void SetTable(DataTable table)
{
table2 = table;
// Your code to fill DGV source with table2
}
Form1
中的用法可能如下所示:
form2.SetTable(this.table);
form2.ShowDialog();