我正在尝试开发一个windows窗体应用程序。在这里,我想同时调用form 1和form 2的变量。我将vale转换为ComputerId变量。
namespace ComData
{
public partial class addnew : Form
{
string ConnString = "Server=localhost;Database=machinedetails;UID=root;Encrypt=true;";
public int ComputerId { get; set; }
public addnew()
{
InitializeComponent();
}
private void btnnext_Click(object sender, EventArgs e)
{
using (MySqlConnection conn = new MySqlConnection(ConnString))
{
using (MySqlCommand comm = new MySqlCommand())
{
if (this.txtbranch.Text != "" && this.txtcostcenter.Text != "")
{
try
{
MySqlParameter branchparam = new MySqlParameter("@branch", MySqlDbType.VarChar, 16);
MySqlParameter costcenterparam = new MySqlParameter("@costcenter", MySqlDbType.VarChar, 16);
comm.Connection = conn;
conn.Open();
comm.CommandText = "INSERT INTO computerdetails(branch,costcenter) VALUES (@branch, @costcenter);Select last_insert_id();";
comm.Parameters.Add(branchparam);
comm.Parameters.Add(costcenterparam);
comm.Prepare();
String branch = txtbranch.Text;
String costcenter = txtcostcenter.Text;
comm.Parameters[0].Value = branch;
comm.Parameters[1].Value = costcenter;
MySqlDataReader reader = comm.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
ComputerId = Convert.ToInt32(reader[0]);
MessageBox.Show("value is" + ComputerId);
}
this.Hide();
newdetails nd = new newdetails();
nd.ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please fill the values");
}
}
}
}
}
}我想知道如何在Form2中调用这个ComputerId变量。请帮助我。谢谢..
发布于 2014-09-15 14:01:12
此代码块属于打开addnew-form的form2
addnew testObj = new addnew(); //init
testObj.show() //or testObj.showDialog();
int id = testObj.ComputerId; //getting the id发布于 2014-09-15 14:08:15
您可以将参数化构造函数添加到newdetails窗体。然后将整数值传递到那里。如下所示:
// In newdetails form
private int computerId;
public newdetails(int compId){
computerId = compId;
}
// in addnew form
newdetails nd = new newdetails(ComputerId);发布于 2014-09-15 14:13:02
在newdetails表单中:
private addNew _addNew { get; set; }
public newdetails(addNEw parent)
{
InitializeComponent();
_addNew = parent;
}
//you can access any public variable at addNew form with:
int test = _addNew.PublicVariableName在addnew表单中:
newetails x = new newdetails(this);
x.Show();https://stackoverflow.com/questions/25841580
复制相似问题