我有一个xml文件,如下所示:
<Accounts>
<Account Id="1">
<UserName>xxx@Hotmail.com</UserName>
<Password>xxx</Password>
<AddingDate>06 Mart 2015 Cuma</AddingDate>
<AccountType>Hotmail</AccountType>
</Account>
我使用Dictionarylist来保存用户名和密码值。我只显示这样的用户名:
private void AddAccounts(CheckedListBox chkListBox)
{
XDocument doc = XDocument.Load("UserAccounts.xml");
Dictionary<string, string> dict = doc.Descendants("Account")
.GroupBy(x => x.Element("UserName"), y => y)
.ToDictionary(x => x.Key.Value, y => y.First().Element("Password").Value);
foreach (var v in dict)
{
checkedListBox1.Items.Add(v.Key);
}
}
然后。一旦SelectedIndexChanged事件被触发,我试图从checkedListBox获取这个DictionaryList。就像这样
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
XDocument doc = XDocument.Load("UserAccounts.xml");
var dataSource = checkedListBox1.DataSource as Dictionary<string, string>;
if (c != null)
{
var password_ = c.Where(x => x.Key.Equals("")).Select(x => x.Value).FirstOrDefault();
}
}
问题在于以下部分
var dataSource = checkedListBox1.DataSource as Dictionary<string, string>;
为空。断点永远不会进入这部分
if (c != null){}
这部分。我很确定AddAccounts功能是我测试过的吗
答案 0 :(得分:0)
您无法将项目添加到CheckedListBox并将其作为DataSource返回。
如果要将Dictionary设置为CheckedListBox的DataSource,您可以像这样分配它
// delete this lines...
//foreach (var v in dict)
//{
// checkedListBox1.Items.Add(v.Key);
//}
checkedListBox1.DataSource = new BindingSource(dict, null);
checkedListBox1.DisplayMember = "Value";
checkedListBox1.ValueMember = "Key";
并且在您的SelectedIndexChanged事件中,您必须像这样分配dataSource
var dataSource = checkedListBox1.DataSource as BindingSource;
var dict = dataSource.DataSource as Dictionary<string, string>;
希望这有帮助!