Search code examples
c#messagebox

MessageBox.Show not working on button click


everybody. :)

Totally new to C# right now, so I apologize for the probable idiocy of this question. :P I've done quite a bit of searching over the past couple of hours and not been able to find anything that has solved my issue, unfortunately.

I've been running through some basic C# guides, and I'm going through the creation of a simple Windows Form Application with a button that, when clicked, displays a MessageBox with a short phrase in it. Oddly, though, when I debug the app and click the button, nothing happens. In my searches, I've seen many situations where people have the MessageBox show with no text; in this situation, however, absolutely nothing is happening. It acts as though there is no action being applied whatsoever.

I'm using VSC# 2010 Express. I tried this with fresh projects and installs on both my Windows 7 machine and my XP machine, same results on both.

Thanks for your help! Code pasted below.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Here's a message??");
        }
    }
}

Solution

  • Hook button1_click Event Handler to the Click Event of your Button

        public Form1()
        {
            InitializeComponent();
            button1.Click += new EventHandler(button1_Click); 
            //add above line
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Here's a message??");
        }
    

    What was happening was that you just wrote your event coding but there was no call for it.

    With this line button1.Click += new EventHandler(button1_Click); when click happens it will execute private void button1_Click(object sender, EventArgs e) function.