[英]TabPage keeps being created. C#
即使標簽頁已經存在於我的標簽控件中,TabPage仍會繼續創建。 請考慮以下我的代碼:
void button1_Click(object sender, EventArgs e)
{
TabPage tabPage = new TabPage();
tabPage.Name = "TestNewTab";
tabPage.Text = "Tab Page";
// Check if the tabpage is not yet existing
if (!tabControl1.TabPages.Contains(tabPage))
{
// Add the new tab page
tabControl1.TabPages.Add(tabPage);
}
}
我的代碼有什么問題? 謝謝。
我的猜測是TabPages.Contains正在檢查對象引用,因為每次都實例化一個新的TabPage時,它將不會是同一對象。 嘗試遍歷選項卡頁面並比較Name屬性。
問題是.Contains
在查找類似TabPage
的引用類型時會檢查是否等於引用,而不是等於相等的值。 解決問題的一種簡單方法是執行以下操作:
TabPage tabPage;
void button1_Click(object sender, EventArgs e)
{
// Check if the tabpage doesn't exist yet:
if (tabPage == null)
{
// Create the tab page:
tabPage = new TabPage();
tabPage.Name = "TestNewTab";
tabPage.Text = "Tab Page";
// Add the new tab page:
tabControl1.TabPages.Add(tabPage);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.