我正试图将一个整数传递到C#中的另一种形式中。在检查了用户的登录凭据后,我想获得is ID,然后将其传递到另一个表单中。但是,我收到一个错误,说我试图传递的值是一个未分配的本地变量。这是我的代码:
FORM 1
private void button1_Click(object sender, EventArgs e)
{
if (u.Text == "" || p.Text == "")
{
MessageBox.Show("Please enter username and password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
try
{
// Query for registration
string view = "SELECT * FROM person WHERE username = '" + u.Text + "' AND password = '" + p.Text + "';";
// Start SQL connection
MySqlConnection myConn = new MySqlConnection(connectionString);
MySqlCommand myCommand = new MySqlCommand(view, myConn);
MySqlDataAdapter da = new MySqlDataAdapter(myCommand);
MySqlDataReader myReader;
myConn.Open();
myReader = myCommand.ExecuteReader();
if (myReader.HasRows)
{
int id;
while (myReader.Read())
{
id = myReader.GetInt32("person_id");
//person_id = myReader.GetInt("person_id");
MessageBox.Show(id.ToString());
}
myConn.Close();
// Create instance of the form
Form3 dash = new Form3(id); //unassigned local variable id
dash.Show(); // Show the form
this.Hide(); // Hide this current form
}
else
{
MessageBox.Show("Incorrect username or password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
FORM 3
public partial class Form3 : Form
{
int final_id;
public Form3(int id)
{
InitializeComponent();
assignGlobal(id);
}
public void assignGlobal(int b)
{
final_id = b;
MessageBox.Show(final_id.ToString());
}
}
我已经使用MySql.Data.MySqlClient.
导入了,我真的不明白为什么它会显示这个错误。有人能告诉我哪里出了问题吗?我应该更改什么?我们将非常感谢你的帮助。非常感谢。
如果读取器为空,则while循环可能不会执行。因此,您需要显式地为id
:分配一个默认值
int id = 0;
或者您需要使用if else
语句来处理这种情况。
此外,如果您希望只有一个值,我建议您使用ExecuteScalar
而不是ExecuteReader
。
您需要在这里问自己一个问题:如果读取器没有返回任何值,我的程序应该怎么办