如何将相同的变量传递给C#中的其他表单

时间:2017-03-04 01:42:29

标签: c# .net winforms

我想要实现的是当学生登录系统时,系统应该从数据库中获取他/她的studentID。然后在我的“测试形式” - 学生参加考试。系统应将测试详细信息以及将测试进入“测试”表的studentID添加。

问题:我不知道如何将登录表单中的studentID传递给测试表单。

我有一些我试过的代码,这是我研究的结果,但它仍然不适合我:

登录表单代码:[仅相关位是'StudentID'部分]

//gets the info and checks if the input is same as contents in DB
using (MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;database=project;username=root;password=***;"))
{
MySqlCommand cmd = new MySqlCommand("SELECT student.studentID, student.studentUsername, student.studentPassword, student.studentFirstName, student.studentLastName, teacher.teacherUsername, teacher.teacherPassword, teacher.teacherFirstName, teacher.teacherLastName FROM student, teacher WHERE (student.studentUsername = @userName AND student.studentPassword = @passWord) OR (teacher.teacherUsername = @teacherUser AND teacher.teacherPassword = @teacherPass);");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@userName", textboxUsername.Text);
cmd.Parameters.AddWithValue("@passWord", texBoxPassword.Text);
cmd.Parameters.AddWithValue("@teacherUser", textboxUsername.Text);
cmd.Parameters.AddWithValue("@teacherPass", texBoxPassword.Text);
MySqlDataReader DBReader;
cmd.Connection = connection;
connection.Open();
DBReader = cmd.ExecuteReader();
while (DBReader.Read())
{
var teacherFirstName = DBReader.GetString("teacherFirstName");
var teacherLastName = DBReader.GetString("teacherLastName");
var teacherLogin = DBReader.GetString("teacherUsername");
var teacherPass = DBReader.GetString("teacherPassword");
var studentFirstName = DBReader.GetString("studentFirstName");
var studentLastName = DBReader.GetString("studentLastName");
var studentLogin = DBReader.GetString("studentUsername");
var studentPass = DBReader.GetString("studentPassword");
string studentID = DBReader.GetString("studentID");
if (teacherLogin == textboxUsername.Text && teacherPass == texBoxPassword.Text)
{
 MessageBox.Show("Welcome " + teacherFirstName + " " + teacherLastName);
 this.Hide();
 TeacherHomepage Form = new TeacherHomepage();
 Form.Show();
}
else if (studentLogin == textboxUsername.Text && studentPass == texBoxPassword.Text)
{
  MessageBox.Show("Welcome " + studentFirstName + " " + studentLastName);
  this.Hide();
  Test ss = new Test(studentID);
  ss.Show();
}
  else
{
  MessageBox.Show("username or password invalid");
}

测试表格代码:

public Test(string studentID)
{
  InitializeComponent();
  int StudentID = Convert.ToInt32(studentID);
 }

注意: 登录的东西有效: 我想要与登录的学生使用相同的StudentID,以“test”的形式使用。另外,当StudentID是局部变量时,如何在我的其他函数中使用测试表单中的“studentID”变量?另请注意,我没有使用任何类(OOP)。如果有更简单的方法,请告诉我。

2 个答案:

答案 0 :(得分:1)

您可以将StudentID添加为自动属性或测试表单中的字段。所以它将是--->

{{1}}

答案 1 :(得分:-1)

您可以在课堂中声明一个公共变量,并使用它来存储学生ID的值。你可以在任何你想要的地方使用它。

Public static int student_id;