![](/img/trans.png)
[英]I have a DataGridView on my form that is not being displayed when I run my form. Why?
[英]Why aren't my if statements and MessageBox's not getting hit or displayed when I run my Windows form applications?
我研究了几个常见问题,例如在表单窗口后面显示的消息框,尝试使用不同的 wat 来调用它们,但似乎没有显示它们。 我确定这是我想念的简单东西吗?
应用程序应该打开一个带有列表框和一些项目的表单窗口,如果没有选择任何内容并且您单击按钮,它应该在消息框中显示“请从列表框中选择和项目”,但它没有。
它还应该显示“您确定要关闭吗?” 当您离开表单窗口时,框中的消息。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsDemos
{
public partial class Dialogs : Form
{
public Dialogs()
{
InitializeComponent();
}
private void Dialogs_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Oranges");
listBox1.Items.Add("Grapes");
listBox1.Items.Add("Bananas");
listBox1.Items.Add("Peaches");
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == -1)
{
var msg = "Please select an item from the list box";
MessageBox.Show(msg, this.Text);
return;
}
else
{
label1.Text = listBox1.Text;
}
}
private void Dialogs_FormClosing(object sender, FormClosingEventArgs e)
{
var msg = "Are you sure you want to close?";
if (MessageBox.Show(msg, this.Text, MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
}
}
这应该有效。 您确定您有与该方法相关联的事件吗?
// in file Dialogs.Designer.cs or in Form Property/Events tool window
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Dialogs_FormClosing);
与其让您的Dialogs
类订阅其自己的事件(如Load
和FormClosing
),不如简单地覆盖导致事件首先被触发的OnLoad
和OnFormClosing
方法,这样更简洁(并且可能更不容易出错)。 我测试了这段代码,它产生了您帖子中描述的预期结果。
public Dialogs()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e); // <== The `Load` event you were subscribing to is fired here.
listBox1.Items.Add("Oranges");
listBox1.Items.Add("Grapes");
listBox1.Items.Add("Bananas");
listBox1.Items.Add("Peaches");
// Subscribing to the `Click` event here as an
// alternative to relying on the Designer to do it.
button1.Click += onButton1Clicked;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
base.OnFormClosing(e); // <== The `FormClosing` event is fired here.
var msg = "Are you sure you want to close?";
if (MessageBox.Show(msg, this.Text, MessageBoxButtons.YesNo) == DialogResult.No)
{
e.Cancel = true;
}
}
我也同意到目前为止发布的其他答案,即按钮的Click
事件似乎没有链接。 如上面OnLoad
方法中所示,订阅此事件可能不太容易出错。
private void onButton1Clicked(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == -1)
{
var msg = "Please select an item from the list box";
MessageBox.Show(msg, this.Text);
return;
}
else
{
label1.Text = listBox1.Text;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.