我有一个方法从数据库中提取url名称(varchar),urlID(int)及其Enabled status(bit),并将结果填充到foreach循环上的CheckedListBox。我遇到的问题是checkboxlist似乎只取一个名称及其检查状态。我需要做的是当用户完成对按钮事件的选择时,它会读取CheckedListBox并获取URL 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);
}
}
答案 0 :(得分:6)
步骤1:使用ToString()覆盖创建一个类来保存Name和Id,该覆盖返回Name
public class UrlInfo
{
public string Name;
public int Id;
public bool Enabled;
public override string ToString()
{
return this.Name;
}
}
步骤2:将此类的实例添加到CheckedListBox
UrlInfo u1 = new UrlInfo { Name = "test 1", Id = 1, Enabled = false };
UrlInfo u2 = new UrlInfo { Name = "test 2", Id = 2, Enabled = true };
UrlInfo u3 = new UrlInfo { Name = "test 3", Id = 3, Enabled = false };
checkedListBox1.Items.Add(u1, u1.Enabled);
checkedListBox1.Items.Add(u2, u2.Enabled);
checkedListBox1.Items.Add(u3, u3.Enabled);
第3步:将SelectedItem强制转换为UrlInfo并检索.Id
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
UrlInfo urlInfo = checkedListBox1.Items[e.Index] as UrlInfo;
if (null != urlInfo)
{
urlInfo.Enabled = e.NewValue == CheckState.Checked;
Console.WriteLine("The item's ID is " + urlInfo.Id);
}
}
答案 1 :(得分:1)
您最好创建一个包含string
(您的网址)和int
(ID)的简单类,覆盖ToString()
方法以返回网址,然后添加对象Items
的{{1}}属性。
获得所选对象后,只需将其强制转换为新类,即可访问这两个属性。
类似的东西:
CheckedListBox
然后当你添加对象时:
public class MyClass
{
public string Url { get; set; }
public int Id { get; set; }
public override string ToString()
{
return this.Url;
}
}
答案 2 :(得分:0)
此控件具有Value Member和Display成员。如果您使用Name作为显示成员并将ID用作值成员,我认为您可以执行所需的操作。