[ADO.NET] DTO 屬性裡有null 的 實值型別要小心
當我們類別裡的屬性有null 的實值型別時要小心!!比如下面的int? _Age
[Serializable]
public class Member
{
public string Name { get; set; }
public string Title { get; set; }
private int? _Age = 16;
public int? Age
{
get { return _Age; }
set { _Age = value; }
}
}
當我們用int?時,會造成資料繫結的錯誤,當繫結到控制項時會無法變更控制項的值,這讓我吃了點小苦頭;你想到硬幹的方法了嗎!? 硬幹方法請參考:[Winform][ADO.NET] comboBox 控制項與 enum 的 Data Binding
要硬幹就必須要處理一些動作,
1.先註冊KeyPress以及TextChanged事件
this.txtAge.KeyPress+=new KeyPressEventHandler(txtAge_KeyPress);
this.txtAge.TextChanged+=new EventHandler(txtAge_TextChanged);
2.禁止使用者輸入非數字資料
private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
{
char key = e.KeyChar;
int value = (int)key;
if ((value >= 48 && value <= 57) || value == 46 || value == 8 || value == 43 || value == 45)
e.Handled = false;
else
e.Handled = true;
}
3.寫入資料來源,寫到資料來源之前必須判斷能否轉型成功
private void txtAge_TextChanged(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
string content = textBox.Text;
if (string.IsNullOrEmpty(content))
return;
int index = this._source.Position;
Member member = (Member)this._source[index];
int result = 0;
if (int.TryParse(content,out result))
{
member.Age = int.Parse(content);
}
else
{
textBox.Clear();
}
}
附帶一提的是,使用 TextChanged 時,當每次按下鍵盤成功時就會寫到資料來源,在效能上可能不佳;為了提升效能,可以使用KeyPress事件加入條件判斷,也就是按下某鍵後寫入資料來源,比較常見的應該是輸入Enter鍵
1.取消TextChanged事件
this.txtAge.TextChanged-=new EventHandler(txtAge_TextChanged);
2.在txtAge_KeyPress方法裡增加增加value==13的判斷,表示按下Enter鍵
private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
{
char key = e.KeyChar;
int value = (int)key;
if (value==13)
{
txtAge_TextChanged(this.txtAge,null);
return;
}
if ((value >= 48 && value <= 57) || value == 46 || value == 8 || value == 43 || value == 45)
e.Handled = false;
else
e.Handled = true;
}
後記:
資料繫結固然方便,也能節省掉coding的時間,但對他瞭解若不深很容易就陷入迷失,因為我也是迷失過的其中之一;若非得已還是不要用硬幹交由Data binding來處理會比較好。
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET