[英]Pass Values from Form -> Class -> Form C#
我有2種形式 : V.Batch和V.BatchEdit和一個類 : M.Batch
在V.Batch中,有一個DataGrid。 我想將我從DataGrid獲得的值傳遞給V.BatchEdit ,並且get set方法在M.Batch中 。
這里的問題是該值未在V.BatchEdit中正確傳遞 。 返回0。
這是代碼
M.Batch bt;
public Batch()
{
bt = new M.Batch();
InitializeComponent();
}
private void metroButton3_Click_1(object sender, EventArgs e)
{
bt.batchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());
V.BatchEdit bEdit = new V.BatchEdit();
this.Hide();
bEdit.Show();
}
public int batchNum;
public int BatchNum
{
set { batchNum = value; }
get { return batchNum; }
}
static M.Batch bt = new M.Batch();
DataSet a = bt.getBatch(bt.batchNum);
public BatchEdit()
{
db = new Database();
InitializeComponent();
System.Windows.Forms.MessageBox.Show(bt.batchNum.ToString() + "Batchedit");
try
{
metroTextBox1.Text = a.Tables[0].Rows[0][2].ToString();
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
我是編碼和C#的新手。 我不確定是否將其放置在靜態位置,即使它不應該是靜態的也是如此。
是的,您在此處使用的static
不正確。
看到問題所在的最簡單方法是注意到您兩次調用了new M.Batch()
。 這意味着您的應用程序中有兩個不同的M.Batch
實例。 而且,您在代碼中的任何地方都不會嘗試共享這些實例。
您應該做的是將M.Batch
實例從一種形式傳遞到另一種形式,例如在構造函數中:
// V.Batch
bt.batchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());
V.BatchEdit bEdit = new V.BatchEdit(bt);
this.Hide();
bEdit.Show();
// V.BatchEdit
private M.Batch bt;
private DataSet a;
public BatchEdit(M.Batch batch)
{
this.bt = batch;
this.a = this.bt.getBatch(bt.batchNum)
// Rest of your code here.
}
如果您不需要'M.Batch'類,而僅將其用於將值傳遞給V.BaychEdit,則只需像在M.Batch中所做的那樣在V.BatchEdit中聲明一個公共屬性即可,這個:
V.BatchEdit bEdit = new V.BatchEdit();
bEdit.BatchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());
您的問題是,盡管您使用靜態變量,但仍在向靜態字段分配新實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.