2011-02-01 105 views
1

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

回答

6

第1步:创建一个类来保存姓名和身份证与返回一个ToString()重写名称

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); 
    } 
} 
+0

以上是为了展示这个概念,并不一定完美实现。您可能希望为属性和ID使用属性而不是字段,通过构造函数初始化它们并且不提供用于不变性的setter等。 – 2011-02-01 15:43:14

0

这种控制有一个value成员和显示部件。我认为如果你使用Name作为显示成员,ID作为值成员,你可以做你所需要的。

+0

有心不是显示构件或值构件,我可以一个CheckBoxList控件米奇下看到。 – Steve 2011-02-01 15:34:23

1

你最好创建一个包含string(网址)的简单类和int(标识),覆盖ToString()方法返回的URL,这些对象添加到CheckedListBoxItems财产。 当你得到选定的对象时,你只需将它转换到你的新类中,并且你可以访问这两个属性。

喜欢的东西:

public class MyClass 
{ 
    public string Url { get; set; } 
    public int Id { get; set; } 
    public override string ToString() 
    { 
     return this.Url; 
    } 
} 

然后当你添加的对象:

CBLUrls.Items.Add(new MyClass { Id = URLID, Url = URLName }, enabled); 
相关问题