从表单传递值 - >类 - >表格C#

时间:2015-03-15 21:45:25

标签: c#

我有 2个表单 V.Batch V.BatchEdit 以及 Class M.Batch

V.Batch 中有一个DataGrid。我想将从DataGrid获取的值传递给 V.BatchEdit ,并且get set方法位于 M.Batch

这里的问题是该值未在 V.BatchEdit 中正确传递。它返回0。

这是代码

V.Batch:

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();

    }

M.Batch:

public int batchNum;

public int BatchNum
    {
        set { batchNum = value; }
        get { return batchNum; }
    }

V.BatchEdit

 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#的新手。我不确定我是否放置静电,即使它不应该是静态的或什么的。

2 个答案:

答案 0 :(得分:0)

是的,您在这里使用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.
}

答案 1 :(得分:0)

如果您不需要'M.Batch'类用于其他内容而您只使用它将值传递给V.BaychEdit,只需在V.BatchEdit中声明一个公共属性,就像在M.Batch中一样。像这样使用它:

V.BatchEdit bEdit = new V.BatchEdit();
bEdit.BatchNum = Convert.ToInt32((metroGrid2.CurrentCell.Value).ToString());

您的问题是,虽然您使用静态,但您仍在为静态字段分配新实例。

相关问题