FinancialResults 為值型別(struct),屬性 getter 傳回複本,無法支援雙向繫結編輯。需改為參考型別(class),getter 傳回內部儲存參考,並實作 INotifyPropertyChanged 通知變更。
同一表單相關控制項應繫結至同一資料來源物件,避免建立多個繫結管理器:
// 錯誤:建立兩個繫結管理器
textBox1.DataBindings.Add("Text", src.Results, "Profit");
textBox1.DataBindings.Add("ForeColor", src, "ProfitForegroundColor");
// 正確:統一使用 src
textBox1.DataBindings.Add("Text", src, "Results.Profit");
textBox1.DataBindings.Add("ForeColor", src, "ProfitForegroundColor");
幾乎所有 Windows/Web 控制項的顯示值、字型、唯讀狀態、位置等均可繫結。建議建立專用型別封裝顯示參數,讓繫結引擎處理傳輸細節。
將 DataGrid 繫結至 DataSet 可自動顯示所有資料、支援多表導覽。若需額外欄位(如格式化姓名),可加入運算欄:
DataTable dt = data.Tables["Employees"];
dt.Columns.Add("EmployeeName", typeof(string), "lastname + ', ' + firstname");
.NET 嘗試自動型別轉換,失敗時靜默還原。可處理 Parse 事件提供回饋:
private void Form1_Parse(object sender, ConvertEventArgs e)
{
try { Convert.ToInt32(e.Value); }
catch
{
MessageBox.Show($"{e.Value} is not an integer");
e.Value = 0;
}
}
Format 事件可在資料流向控制項前格式化顯示字串。
.NET 提供完整繫結架構,開發者專注於建立描述顯示參數的資料型別,其餘交給 WinForms/WebForms 處理。勿手寫控制項與資料來源間的傳輸程式碼。