例如,假设我在窗体的主屏幕上有一个datagridview和PC组件列表,以及用于从此dgv添加,删除或修改组件的按钮。我希望用户能够从datagridview中选择一行,然后单击Modify按钮,这将打开ModifyComponent表单,并且所选组件的详细信息将填充在各个文本框中。因此,我希望将数据从选定的行中提取到ModifyComponent表单中。到目前为止,这就是我尝试过的方式。我以MainScreen形式创建了此方法(行索引与Components绑定列表中的ComponentID属性相同):
public int getData()
{
int component = ComponentsGridView.SelectedRows[0].Index);
return component;
}
然后在ModifyComponent表单中,我使用Inventory类中的lookupComponent方法,该方法获取组件ID并从“组件”列表中拉出正确的组件:
Inventory.lookupComponent(MainScreen.getData());
然后,我将编写代码以将每个属性放入正确的文本框中,但出现错误“非静态字段,方法或属性MainScreen.getData需要对象引用”。解决此问题的最佳方向是什么?解决该问题的另一种方式是什么?
答案 0 :(得分:0)
这是一种可行的方法(C#翻译)。
几件事:
C#
// Declare In Parent form (outside functions, in the head of class)
public DataTable dt = new DataTable(); // create *public* datatable
// Get data any way you like into datatable
string cmdTextTC = "SELECT TOP 1000 ID, Name, Componet FROM TestTable; ";
DataSet ds;
ds = DataAccessLayer.GetQueryResultsTC(cmdText);
If ds.Tables.Count > 0 Then
dt = ds.Tables(0)
End If
// Use it for datagrid
this.DataGridViewComponents.datasource = dt;
// Declare In Child form (outside functions, in the head of class)
public MyParentForm ParentFrm; // link to parent
public Int32 ComponentID; // selected component
// When declaring child form in the parent, remember to set some relations
MyChildForm ChildForm; // child form
ChildForm.ParentFrm = this; // create reference to parent
ChildForm.ComponentID = ComponentsGridView.SelectedRows(O).Index; // Set Selected ID
// Use data in ChildForm
DataRow dr = ParentFrm.dt.rows(ComponentID);
this.NumericUpDownID.Value = System.Convert.ToInt32(dr("ID"));
this.TextBoxName.Text = System.Convert.ToString(dr("Name"));
VB代码
' Declare In Parent form (outside functions, in the head of class)
Public dt As New DataTable ' create *public* datatable
' Fill it any way you like (here I use a declared function)
Dim cmdTextTC As String = "SELECT TOP 1000 ID, Name, Componet FROM TestTable; "
Dim ds As DataSet
ds = DataAccessLayer.GetQueryResultsTC(cmdText)
If ds.Tables.Count > 0 Then
dt = ds.Tables(0)
End If
' Use it for datagrid
Me.DataGridViewComponents.datasource = dt
' Declare In Child form (outside functions, in the head of class)
Public ParentFrm As MyParentForm ' link to parent
Public ComponentID As Int32 ' selected component
' When declaring child form in the parent, remember to set some relations
Dim ChildForm As MyChildForm ' child form
ChildForm.ParentFrm = Me ' create reference to parent
ChildForm.ComponentID = ComponentsGridView.SelectedRows(O).Index ' Set Selected ID
' Use data in ChildForm
Dim dr As DataRow = ParentFrm.dt.rows(ComponentID)
Me.NumericUpDownID.Value = CInt(dr("ID"))
Me.TextBoxName.Text = CStr(dr("Name"))