2011-02-01 158 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); 
相關問題