我试图在取消选中复选框时删除值。 我的代码:
var words = new List<string>();
if (ckbAnswer1.Checked)
words.Add(" -A,");
if (ckbAnswer2.Checked)
words.Add("B,");
if (ckbAnswer3.Checked)
words.Add("C");
treeView1.SelectedNode.Text += treeView1.SelectedNode.Text +string.Join(" ", words);
返回Question 1 - A,B,C
,但是,我想取消选中&#34; A&#34;,这应该从Question 1 - A,B,C
中删除它。我该怎么做?
答案 0 :(得分:1)
您应该订阅CheckedChanged
事件和内部方法检查:
private void CheckBoxA_CheckedChanged(Object sender, EventArgs e)
{
if (checkboxA.Checked)
{
words.Add("word");
}
else
{
words.Remove("word");
}
treeView1.SelectedNode.Text = "Question 1 - ";
treeView1.SelectedNode.Text += string.Join(" ", words);
}
答案 1 :(得分:0)
我建议使用一些密钥而不仅仅是基于文本的问题。
List<KeyValuePair<Guid, string>> words = new List<KeyValuePair<Guid, string>>();
ckbAnswer1.Tag = Guid.NewGuid().ToString();
if (ckbAnswer1.Checked)
questions.Add(new KeyValuePair<Guid, string>(ckbAnswer1.Tag, "A"));
else//Unchecked
words.Remove(words.Where(kv => kv.Key == ckbAnswer1.Tag));
treeView1.SelectedNode.Text += treeView1.SelectedNode.Text + string.Join(", ", words.Select(kvp => kvp.Value));
答案 2 :(得分:0)
如果您将此CheckChanged
事件分配给每个Checkbox
:
private void ckbAnswer_CheckedChanged(object sender, EventArgs e)
{
UpdateNode();
}
然后添加方法:
private void UpdateNode()
{
var words = new List<string>();
if (ckbAnswer1.Checked)
{
words.Add("A");
}
if (ckbAnswer2.Checked)
{
words.Add("B");
}
if (ckbAnswer3.Checked)
{
words.Add("C");
}
var answers = " - none";
if (words.Count > 0) {
answers = " - " + string.Join(", ", words);
}
treeView1.SelectedNode.Text = treeView1.SelectedNode.Tag.ToString() + answers;
}
此行应添加到最初填充TreeView的位置:
treeView1.SelectedNode.Tag = treeView1.SelectedNode.Text;
那应该做你想做的事。
&#39;棘手&#39;部分是确保您保留原始Node.Text的副本。