﻿# 避免 DropDownList 指定無效的 SelectedValue

去年有寫過一篇 [DropDownList 在作 DataBind 的時候發生 Exception](/post/2007/11/08/DropDownList-Exception-when-Perform-DataBinding)，是還蠻實用的，不過原則上來說程式盡量不要讓他發生 Exception 比較好，因為丟出例外事件是十分消耗系統資源的，今天另外分享另一個小技巧。

如果原本指定給 SelectedValue 的程式長這樣：

```
DropDownList1.SelectedValue = Request.QueryString["ID"];
```

建議可以改成這樣：

```
string id = Request.QueryString["ID"];
ListItem item = DropDownList1.Items.FindByValue(id);
if (item != null) {
    DropDownList1.SelectedValue = id;
}
```

你也可以將這段程式包成一個 Helper 靜態方法，方便在專案中使用。

**相關連結**

-   [DropDownList 在作 DataBind 的時候發生 Exception](/post/2007/11/08/DropDownList-Exception-when-Perform-DataBinding)
-   [例外狀況的設計方針](http://msdn.microsoft.com/zh-tw/library/ms229014.aspx) - .NET Framework 開發人員手冊
