[英]How to display a selected record in a textbox
因此,我试图将表中的选定记录放入文本框中,更具体地说,将用户的名字和ID放入文本框中。
textBox2显示名字,textBox3显示ID。 从技术上讲,它可以工作,但始终显示表中的LAST记录,而不是用户用于登录的特定记录。
例如,假设应该将textBox2显示为“ Bill”和“ 1”,则textBox2显示为“ Bob”,而textBox3显示为“ 2”。
在此先感谢您的帮助。
void login()
{
string firstName;
string studentID;
string path = "Data Source = LOCALHOST; Initial Catalog =library ; username='root';password=''";
MySqlConnection con = new MySqlConnection(path);
string sqlSelect = "select * from users";
MySqlCommand sqlCommand = new MySqlCommand(sqlSelect, con);
try
{
con.Open();
using (MySqlDataReader sqlReader = sqlCommand.ExecuteReader())
{
while (sqlReader.Read())
{
firstName = sqlReader["FirstName"].ToString();
studentID = sqlReader["ID"].ToString();
textBox2.Text = firstName;
textBox3.Text = studentID;
}
}
}
catch
{
con.Close();
}
}
以第一种形式登录的代码。
void login()
{
string userName;
string password;
string userType;
string path = "Data Source = LOCALHOST; Initial Catalog =library ; username='root';password=''";
MySqlConnection con = new MySqlConnection(path);
string sqlSelect = "select * from users WHERE Username = '" + textBox1.Text + "' AND Password = '" + textBox2.Text + "'";
MySqlCommand sqlCommand = new MySqlCommand(sqlSelect, con);
try
{
con.Open();
using (MySqlDataReader sqlReader = sqlCommand.ExecuteReader())
{
while (sqlReader.Read())
{
userName = sqlReader["Username"].ToString();
password = sqlReader["Password"].ToString();
userType = sqlReader["UserType"].ToString();
if (textBox1.Text == userName)
{
if (textBox2.Text == password)
{
if (comboBox1.Text == userType)
{
if (userType == "Admin")
{
MessageBox.Show("Logged in as Admin", "Login");
Admin frmAdmin = new Admin();
this.Hide();
frmAdmin.Show();
}
else if (userType == "Student")
{
MessageBox.Show("Logged in as Student", "Login");
Student frmStudent = new Student();
this.Hide();
frmStudent.Show();
}
}
}
}
}
}
}
finally
{
con.Close();
}
}
您正在从表中选择所有用户。 您需要一些WHERE逻辑来将结果集限制为1行。 否则,您的while循环将迭代直到返回最后一条记录,这些将成为显示的值。
您正在获取查询中的所有用户数据
string sqlSelect = "select * from users";
当您应该仅从登录用户那里获得一个时,例如
string sqlSelect = "select * from users WHERE id=<ID of user logged in>";
while循环使用表上每个用户的信息覆盖/更新textBox2和textBox3,因此,完成后,它始终在最后一个用户上。 因此,如果仅让用户登录,则信息将正确显示。 希望我能帮上忙。
您将一遍又一遍地覆盖TextBox值,直到到达最后一个。 如果只想在文本框中显示第一条记录,请使用以下查询:
string sqlSelect = "select TOP 1 * from users";
如果要搜索特定用户,请尝试:
string sqlSelect = string.Format("select * from users where username={0}",username); //supposed the login-ed user name is saved in username
要么
string sqlSelect = string.Format("select * from users where id={0}",userId); //supposed the login-ed user id is saved in userId
更新资料
为了保留用户名和其他信息,请使用public string
,并以所需的所有形式使用它。 您可以在单独的类中对其进行初始化:
public static string Username;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.