使用close(X)按钮创建自定义datagridview弹出控件

时间:2013-11-01 09:55:27

标签: c# winforms visual-studio-2010

我想在我的Windows窗体应用程序中创建一个控件。此控件包含一些数据作为datagridview控件。但我的要求是将此控件显示为弹出控件。下面是这个屏幕截图。

enter image description here

请帮助我克服这个问题。任何帮助表示赞赏。

注意: - 我希望我的表单与上面的屏幕截图相同意味着我只希望我的datagridview可见,而且我不想要表单标题及其边框。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码创建自己的PopupForm。

要删除边框,请使用FormBorderStyle

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

然后放置你的DataGridView和你的按钮: Example Popup

使用DataGridView的Dock-Property填写表单:

yourDataGridViewControl.Dock = DockStyle.Fill;

将按钮放在右上角并创建EventHandler以抓住Click-Event

button_close.Click += button_close_Click;
private void button_close_Click(object sender, EventArgs e)
{
    this.Close();
}

在您的主体中: 创建以下两个字段:

PopupForm popup; //PopupForm is the name of your Form
Point lastPos; //Needed to move popup with mainform

使用以下代码在按钮的位置显示弹出窗口:

void button_Click(object sender, EventArgs e)
{
    if(popup != null)
        popup.Close(); //Closes the last open popup

    popup = new PopupForm();
    Point location = button.PointToScreen(Point.Empty); //Catches the position of the button
    location.X -= (popup.Width - button.Width); //Set the popups X-Coordinate left of the button
    location.Y += button.Height; //Sets the location beneath the button
    popup.Show();
    popup.TopMost = true; //Is always on top of all windows
    popup.Location = location; //Sets the location

    if (popup.Location.X < 0) //To avoid that the popup 
        popup.Location = new Point(0, location.Y); //is out of sight
}

创建一个EventHandler以捕获MainForm的Move-Event并使用以下方法将您的弹出窗口移动到您的MainForm(Credit goes to Hans Passant):

private void Form1_LocationChanged(object sender, EventArgs e)
{
    try
    {
        popup.Location = new Point(popup.Location.X + this.Left - lastPos.X,
            popup.Location.Y + this.Top - lastPos.Y);
        if (popup.Location.X < 0)
            popup.Location = new Point(0, popup.Location.Y);
    }
    catch (NullReferenceException)
    {
    }
    lastPos = this.Location;
}

您可以在这里获得Demoproject:LINK