我一直在尝试将文本文件加载到组合框中,然后创建一个按钮,将我在组合框中所做的任何更改保存回文本文件。
问题是,当我在组合框中输入内容时,所选的“项目”不会更新。我可以更改句子,但是一旦我点击“保存”按钮,它也会更新组合框,它会在我编辑它之前返回。
此外,当我编辑组合框并单击下拉箭头时,它会再次显示文本文件的内容,而没有我编辑过的句子。
我一直在寻找一段时间,但到目前为止似乎没有人知道如何做到这一点。 :P
private void cbBanken_SelectedValueChanged(object sender, EventArgs e)
{
this.cbBanken.Update();
}
我觉得这样的事情可能有用,但它没有做任何事情。我确实设法在更改后将一个新项目添加到列表中,但这不是我想要的。我希望能够编辑项目,而不是添加新项目。
我希望这足够详细。谢谢你的时间!
编辑:好吧,还有一件事:“它只会更新我更改的第一个字符。所以如果我在任何地方使用退格键,它会更新,然后我必须重新启动它才会再次更新。此外,它会去在组合框线的最左边,这可能很烦人..如果有人知道如何修复它,我会非常感激。“
我目前正在使用此代码:
private void comboBox1_TextChanged(object sender, EventArgs e)
{
if(comboBox1.SelectedIndex>=0)
{
int index = comboBox1.SelectedIndex;
comboBox1.Items[index] = comboBox1.Text;
}
}
答案 0 :(得分:3)
ComboBox.Update方法只是重绘组合框区域。 据我所知,您想在运行时更改组合框选定的项目。在这种情况下,您可能希望使用TextUpdate事件。 Combobox选择的索引会自动停止编辑。所以还有另一种方式。跟踪价值变化。这是一段代码:
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;
}
答案 1 :(得分:0)
如果您在代码隐藏和bind to that property中创建属性会怎样?
第一次胜利是更好的可调试性,第二次胜利是你可以决定在获取/设置数据时该怎么做。
答案 2 :(得分:0)
我遇到了类似的问题:我有Winforms Combo框,VB.Net,Style = DropDown,我想在编辑框中进行更改以更改实际的列表项。
我还有多个组合框,我想要有相同的行为。
以下是我采用上述方法的方法:
Public Class frmDocEntry
...
Private lastIdx As Integer = -1
...
Private Sub cbAnyMV_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbRGBStringMV.Enter, cbRGBIntegerMV.Enter, cbRGBFloatMV.Enter, cbRGBDateMV.Enter
' comboBox.SelectedIndex will get *reset* to -1 by text edit
lastIdx = sender.SelectedIndex
End Sub
Private Sub cbAnyMV_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbRGBStringMV.Leave, cbRGBIntegerMV.Leave, cbRGBFloatMV.Leave, cbRGBDateMV.Leave
If lastIdx >= 0 Then
sender.Items(lastIdx) = sender.Text
End If
lastIdx = -1
End Sub
Private Sub cbAnyMV_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbRGBStringMV.SelectedIndexChanged, cbRGBIntegerMV.SelectedIndexChanged, cbRGBFloatMV.SelectedIndexChanged, cbRGBDateMV.SelectedIndexChanged
lastIdx = sender.SelectedIndex
End Sub