我一直在尝试将文本文件加载到组合框中,然后创建一个按钮,将我在组合框中所做的任何更改保存回文本文件.
问题是,当我在组合框中输入内容时,所选的"项目"不会更新.我可以更改句子,但是一旦我点击"保存"按钮,它也会更新组合框,它会在我编辑它之前返回.
此外,当我编辑组合框并单击下拉箭头时,它再次显示文本文件的内容,没有我编辑的句子.
我一直在寻找一段时间,但到目前为止似乎没有人知道如何做到这一点.:P
private void cbBanken_SelectedValueChanged(object sender, EventArgs e)
{
this.cbBanken.Update();
}
Run Code Online (Sandbox Code Playgroud)
我觉得这样的东西可能有效,但它没有做任何事情.我确实设法在更改后将一个新项目添加到列表中,但这不是我想要的.我希望能够编辑项目,而不是添加新项目.
我希望这足够详细.感谢您的时间!
编辑:好的,还有一件事:"它只会更新我改变的第一个字符.所以如果我在任何地方使用退格键,它会更新,然后我必须重新启动它才会再次更新.此外,它会转到远处在组合框线的左边,这可能非常烦人.如果有人知道如何修复它,我真的很感激."
我目前正在使用此代码:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex>=0)
{
int index = comboBox1.SelectedIndex;
comboBox1.Items[index] = comboBox1.Text;
}
}
Run Code Online (Sandbox Code Playgroud)
ComboBox.Update 方法只是重绘组合框区域。据我了解,您想在运行时更改组合框所选项目。在这种情况下,您可能需要使用 TextUpdate 事件。组合框选定的索引将自动停止编辑。所以还有另一种方法。跟踪值的变化。这是一个代码片段:
private int editedIndex = -1;
private String editString = "";
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (editedIndex == comboBox1.SelectedIndex) return;
if(editedIndex>0) comboBox1.Items[editedIndex] = editString; //Change the previous item
if(comboBox1.SelectedIndex>=0) //get new item parameters
{
editedIndex = comboBox1.SelectedIndex;
editString = comboBox1.Items[editedIndex].ToString();
}
}
private void comboBox1_Leave(object sender, EventArgs e)
{
if(editedIndex>=0)
comboBox1.Items[editedIndex] = editString;
}
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
if (editedIndex >= 0)
{
editString = comboBox1.Text;
}
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyData==Keys.Enter&&editedIndex>=0)
comboBox1.Items[editedIndex] = editString;
}
Run Code Online (Sandbox Code Playgroud)