如何在文本框中显示所选记录
本文关键字:显示 记录 文本 | 更新日期: 2023-09-27 18:33:51
所以我尝试将表中的选定记录放入文本框中,更具体地说,是用户的名字和他们的 ID。
textBox2 显示名字,textBox3 显示 ID。从技术上讲,它可以工作,但它始终显示表中的 LAST 记录,而不是用户用于登录的特定记录。
例如,textBox2 显示"Bob",textBox3 显示"2",而它们应该显示"Bill"和"1"。
提前感谢任何帮助。
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,因此当它完成时,它始终在最后一个用户上。因此,如果您只登录用户,则信息将正确显示。希望我有帮助。
您一遍又一遍地覆盖文本框值,直到到达最后一个。如果只想在文本框中显示第一条记录,请使用以下查询:
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;