論壇問題:要在 Form 之間傳值,拿來練習
Project 內容
frmMain layout
frmCustSearch layout
Customer Class
namespace WindowsFormsApplication1
{
public class Customer
{
public int CustID { get; set; }
public string CustName { get; set; }
public string Address { get; set; }
}
}
frmMain C# Codenamespace WindowsFormsApplication1
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnCustSearch_Click(object sender, EventArgs e)
{
ClearControlValue();
frmCustSearch CustSearch = new frmCustSearch();
if (CustSearch.ShowDialog() != DialogResult.OK)
return;
var customer = CustSearch.RetValue;
txtCustID.Text = customer.CustID.ToString();
txtCustName.Text = customer.CustName;
txtAddress.Text = customer.Address;
}
void ClearControlValue()
{
foreach (Control ctl in Controls.OfType<TextBox>())
{
if ((ctl is TextBox txt) == false)
continue;
txt.Text = string.Empty;
}
}
}
}
frmCustSearch C# Codenamespace WindowsFormsApplication1
{
public partial class frmCustSearch : Form
{
public frmCustSearch()
{
InitializeComponent();
}
// 紀錄使用者點選的是哪一筆資料
public Customer RetValue { get; set; }
private void frmCustSearch_Load(object sender, EventArgs e)
{
dgvCustomer.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
btnOK.Click += btn_Click;
btnCancel.Click += btn_Click;
dgvCustomer.DataSource = DataGridViewSource();
dgvCustomer.ClearSelection();
}
List<Customer> DataGridViewSource()
{
return
new List<Customer>()
{
new Customer() { CustID = 1, CustName = "客戶1", Address = "台北" },
new Customer() { CustID = 2, CustName = "客戶2", Address = "台中" },
new Customer() { CustID = 3, CustName = "客戶3", Address = "高雄" }
};
}
void btn_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn == null)
return;
DialogResult result = DialogResult.OK;
if (RetValue == null ||
btn.Name == btnCancel.Name)
result = DialogResult.Cancel;
DialogResult = result;
Close();
}
private void dgvCustomer_CellClick(object sender, DataGridViewCellEventArgs e)
{
RetValue = new Customer()
{
CustID = (int)dgvCustomer.CurrentRow.Cells[ColCustID.Name].Value,
CustName = (string)dgvCustomer.CurrentRow.Cells[ColCustName.Name].Value,
Address = (string)dgvCustomer.CurrentRow.Cells[ColAddress.Name].Value
};
}
}
}
結果- 參考資料
- 論壇討論 => 有用到 Pattern 的作法
沒有留言:
張貼留言