我有一個方法,從數據庫中拉取url名稱(varchar),urlID(int)及其Enabled狀態(位),並將結果填充到foreach循環上的CheckedListBox。我有的問題是checkedboxlist似乎只有一個名稱和它的檢查狀態。我需要做的是,當用戶完成對按鈕事件的選擇時,它讀取CheckedListBox並獲取URL ID和啓用狀態,以便我可以將其寫回到數據庫。如何獲取CheckedListBox中的項目ID?
這是我使用的代碼:
/// <summary>
/// Create url names in check box list.
/// </summary>
/// <param name="rows"></param>
private void CreateURLCheckBoxes(DataRowCollection rows)
{
try
{
int i = 0;
foreach (DataRow row in rows)
{
//Gets the url name and path when the status is enabled. The status of Enabled/Disabled is setup in the users option page
string URLName = row["URLName"].ToString();
int URLID = Convert.ToInt32(row["URLID"]);
bool enabled = Convert.ToBoolean(row["Enabled"]);
//Adds the returned to rows to the check box list
CBLUrls.Items.Add(URLName, enabled);
}
i++;
}
catch (Exception ex)
{
//Log error
Functionality func = new Functionality();
func.LogError(ex);
//Error message the user will see
string FriendlyError = "There has been populating checkboxes with the urls ";
Classes.ShowMessageBox.MsgBox(FriendlyError, "There has been an Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
以上是爲了展示這個概念,並不一定完美實現。您可能希望爲屬性和ID使用屬性而不是字段,通過構造函數初始化它們並且不提供用於不變性的setter等。 – 2011-02-01 15:43:14