我有一个方法,从数据库中拉取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