簡體   English   中英

C#-編輯后組合框索引更改

[英]C# - Combobox index change after editing

剛才有人回答了我的問題,即如何編輯裝有文本文件的組合框,以及如何保存最近編輯的行。

C#:實時組合框更新

現在的問題是,我只能在更新前更改一個字母,然后selectedindex更改為-1,因此我必須在下拉列表中選擇我正在再次編輯的行。

希望有人知道為什么它會改變索引,以及如何阻止它這樣做。

就我對問題的理解而言,您可以做一件事。 在comboBox1_TextChanged方法中,無需放置先前的代碼,您只需設置一個布爾變量,例如將textChangedFlag設置為true,然后將此變量的默認值設置為false。 然后使用KeyDown事件編輯組合框項。 我將給出示例代碼。

樣例代碼:

if (e.KeyCode == Keys.Enter)
        {
            if (textChangedFlag )
            {
                if(comboBox1.SelectedIndex>=0)
                {
                    int index = comboBox1.SelectedIndex;
                    comboBox1.Items[index] = comboBox1.Text;
                    textChangedFlag = false;
                }

            }
        }

您可以將此代碼放入KeyDown事件處理程序方法中。 希望能幫助到你

private int currentIndex;

public Form1()
{
    InitializeComponent();

    comboBox1.SelectedIndexChanged += RememberSelectedIndex;
    comboBox1.KeyDown += UpdateList;
}

private void RememberSelectedIndex(object sender, EventArgs e)
{
    currentIndex = comboBox1.SelectedIndex;
}

private void UpdateList(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter && currentIndex >= 0)
    {
        comboBox1.Items[currentIndex] = comboBox1.Text;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM