2013-11-01 58 views
0

我想在我的Windows窗體應用程序中創建一個控件。該控件包含一些數據作爲datagridview控件。但我的要求是將此控件顯示爲彈出控件。下面是這個的屏幕截圖。使用close(X)按鈕創建自定義datagridview彈出控件

enter image description here

請幫我解決這個問題。任何幫助讚賞。

注意: - 我希望我的表單與上面的屏幕截圖相同意味着我只希望我的datagridview可見,並且我不希望表單標題及其邊框。

+0

凡到底是什麼問題?你可以用'form.Show()'顯示你的表單,然後設置它的位置。 –

+0

@Jens Kloster我想彈出與上面的屏幕截圖相同的內容。如果我將這個datagridview添加到窗體窗體中,它會向我顯示窗體的標題欄和窗體的邊框,所以我希望彈出窗口與屏幕截圖完全相同。 –

回答

1

您可以使用以下代碼創建自己的PopupForm。

要刪除邊框使用FormBorderStyle

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

然後把你的DataGridView和你的按鈕那樣: Example Popup

使用的DataGridView的Dock屬性來填寫表格:

yourDataGridViewControl.Dock = DockStyle.Fill; 

將您的按鈕放在右上角並創建一個EventHandler以捕捉Click-Event

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

在你的MainForm: 創建以下兩個領域:

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 
} 

創建一個事件處理程序捕捉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