Form1 輸入就診號(ID),點擊確定打開 Form2 並顯示該 ID 對應的數據庫完整信息。
// Form1.cs
public partial class Form1 : Form {
private string _id;
public string PatientID {
get { return _id; }
set { _id = value; }
}
private void btnConfirm_Click(object sender, EventArgs e) {
PatientID = txtID.Text; // 賦值
Form2 frm2 = new Form2();
frm2.Show();
this.Hide();
}
}
// Form2.cs
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
LoadData();
}
private void LoadData() {
Form1 frm1 = (Form1)Application.OpenForms["Form1"];
if (frm1 != null) {
string id = frm1.PatientID;
// 使用 id 查詢數據庫並綁定控件
// string sql = "SELECT * FROM Patient WHERE ID = @id";
// ...
}
}
}
Form2 frm2 = new Form2(txtID.Text); 在 Form2 構造函數接收。優先使用構造函數傳參,語義清晰且避免依賴窗體實例名稱。數據庫查詢務必使用參數化命令防注入。