简体   繁体   中英

Why textbox click event not firing

I have a textbox and it's readonly. When I click on I want it to call my button click event:

private void tbFile_Click(object sender, EventArgs e)
{
    //btnBrowse_Click(sender, e);
    MessageBox.Show("test");
}

When click on the textbox, nothing happens. How do I fix it?

Update:

private void btnBrowse_Click(object sender, EventArgs e)
{
    openFile();
}

private void tbFile_Click(object sender, EventArgs e)
{
    //btnBrowse_Click(sender, e);
    if (tbFile.Text != "")
    {
        openFile();
    }
}

public void openFile()
{
    var FD = new System.Windows.Forms.OpenFileDialog();
    FD.Filter = "DBF Files|*.DBF";
    FD.InitialDirectory = @"C:\";

    if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        string fileToOpen = FD.FileName;
        tbFile.Text = fileToOpen;
    }
}

When I hit browse button and select a file, the browse file window comes up again. So it's appearing twice now and the textbox click is still not working.

There is no reason that can be inferred from the information you provided why you shouldn't trigger the openFile() method when you click on the tbFile control.

The fact that the textbox is set to readonly does not stop it from raising the click event in any way.

The only possibility is that the method is not assigned to the click event of the control.

Make sure in the event properties of the control that the click event is indeed assigned to the "tbFile_Click" method.

Just because there exsits a method that's called the same as a control but has "_Click" added does not make it get executed unless you specifically tell c# you want to associate that method with the click event of the control.

When you assign the method through the event window, C# generates a code file behind the scenes that adds the callback to that specific event.

您应该使用btnBrowse.PerformClick()方法来模拟用户点击,而不是调用处理程序。

The default I got from VS 2013 was a 'MouseClick' function so this works:

    private void btnBrowse_Click(object sender, EventArgs e)
    {     
        MyAwesomeFunction(sender);
    }

    private void tbFile_MouseClick(object sender, MouseEventArgs e)
    {     
        MyAwesomeFunction(sender);
    }

    private void MyAwesomeFunction(object sender)
    {
        MessageBox.Show("test");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM