[英]pass new value from form1 to form2 which was on the same record from the database
我是一個初學者。 我剛剛為圖書館應用創建了登錄表單。
我的登錄表單包含ID,通過和登錄按鈕。 這是我的登錄按鈕腳本。
string userid1 = userid.Text;
string password1 = userpwd.Text;
SqlCommand cmd = new SqlCommand("select id_user,pwd_user from tb_user where id_user='" + userid.Text + "'and pwd_user='" + userpwd.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login success!");
var myForm = new Form2();
this.Hide();
myForm.Show();
}
我的登錄表中的數據庫屬性是:id,pass和name。 有人可以告訴我或指導我登錄表單2后如何將id值傳遞給name值嗎?
我通常在這種情況下為From2做2個構造函數,並設置數據/用戶方法:
public Form2()
{
InitializeComponent();
}
public Form2(string id, string name /* other arguments */) : this()
{
SetUser(id, name);
}
public void SetUser(string id, string name /* other arguments */)
{
this.Text = $"user logged: {name} ({id})";
//do stuff
}
然后像這樣調用(在您的代碼中):
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login success!");
var myForm = new Form2(id, name /* other arguments */);
//or:
//myForm = new Form2();
//myForm.SetUser(id, name);
this.Hide();
myForm.Show();
}
順便說一句:在用戶表中存儲純文本密碼不是一個好主意。 btw2:對於查詢,使用參數而不是從粘貼在一起的字符串構建查詢也是一種好習慣,請在此處查看: https : //msdn.microsoft.com/pl-pl/library/system.data.sqlclient.sqlcommand。參數%28v = vs.110%29.aspx?f = 255&MSPPError = -2147217396
另一種方法
在Form2中創建公共屬性,例如,
public partial class Form2 : Form
{
public string UserId { get; set; }
public string UserName { get; set; }
public Form2()
{
InitializeComponent();
}
}
並從Form1訪問它們
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login success!");
var myForm = new Form2();
var row = dt.Rows[0];
myForm.UserId = Convert.ToString(row["id_user"]);
myForm.UserName = Convert.ToString(row["name_user"])
this.Hide();
myForm.Show();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.