[英]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.