开发者

TextBox loses text when InvokeRequired == false

This is modified code I found on this site.

When appending text to a TextBox and InvoveRequired is false the text will display in the box but the next time the function is called and InvokeRequired is true the text string placed by the first call is lost ("开发者_如何转开发"). Multiple calls when InvokeRequired is true work as expected.

comBox is a type TextBox with multline = true.

Any help would be appreciated.

 public void LogComText(string comText, bool newline)
    {
        if (comBox.InvokeRequired)
        {

            comBox.BeginInvoke(new Action(delegate
            {
                LogComText(comText, newline);
            }));
            return;
        }
        comBox.AppendText(comText);
        if (newline) comBox.AppendText(Environment.NewLine);


    }


This looks like it should work, maybe it has some thing to do with concurrency.
Try using comBox.Invoke(...) instead of comBox.BeginInvoke(...)
Update: The thing is when you use BeginInvoke the method calls may be invoked out of order.
That was wrong, calls to Invoke and BeginInvoke are executed in order.

Edit:
It that doesn´t work make sure you don´t have any other place where you change the text in comBox.

If it still doesn´t work you might have to create a lock to make sure you don´t have two thread simultaneously writing to the textbox.

Something like this:

private static readonly object _comBoxSyncObj = new object();
public void LogComText(string comText, bool newline)
{
    if (comBox.InvokeRequired)
    {
        comBox.Invoke(new Action(delegate
        {
            LogComText(comText, newline);
        }));
        return;
    }
    lock (_comBoxSyncObj)
    {
        comBox.AppendText(comText);
        if(newline) comBox.AppendText(Environment.NewLine);
    }
}

Edit2:
If the problem persists, you can add an event handler for the TextChanged event and put a breakpoint in it to se when the textbox get cleared.

Add this method and an eventhandler for TextChanged on comBox:

private void comBox_TextChanged(object sender, EventArgs e)
{
    if (comBox.TextLength == 0)
    {
        // Set a breakpoint here.
        Trace.WriteLine("TextBox empty");
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜