簡體   English   中英

在 C# 中以編程方式獲取控件名稱

[英]getting control names programmatically in c#

我對 c# .net 比較陌生。 所以如果你想要更多的輸入來回答我的查詢,請告訴我。

1)我想做什么?

我使用的表單在 3 個不同的選項卡中有近 30 個數據網格視圖控件。 datagridview 的名稱如下。 dgView1dgView2dgView3

除了上面的數據網格控件,我還得到了幾個文本框控件,所以在選項卡 1 中更具體一些......我得到了下面的控件項。 txtTabName1txtStrKey1dgView1

現在我正在嘗試編寫一個函數,它將接受一個輸入參數,比如int v_CtrlNum並且使用這個參數我需要掃描一個選項卡中的每個項目並將其添加到一個 ArrayList/Collection。

例如,該函數需要從數據網格視圖中讀取每一行,如下所示

用於數據網格

foreach (DataGridViewRow in dgView+v_CtrlNum )

用於文本框

txtTabName+v_CtrlNum

我想知道我是否正在采取正確的方向做這件事。

您可以查看Controls.Find 方法,注意它返回匹配的控件數組。

Control[] tbp = tabControl1.Controls.Find("txtTabName" + 2,true );
if (tbp.Length > 0)
{
    Control[] dv = tbp[0].Controls.Find("dgView" + 2, true);
}

不完全確定我是否遵循您想要實現的目標,但我認為您只想通過 ID 號獲得控制權,對嗎? 你可以這樣做:

List<Controls> myTabControls = new List<Controls>();
foreach (Control thisControl in this.Controls)
    if (thisControl.Name.Contains(v_CtrlNum.ToString()))
        foreach (Control thisChildControl in thisControl.Controls)
            myTabControl.Add(thisChildControl)thisChildControl

要獲取與v_CtrlNum對應的選項卡中的控件,假設v_CtrlNum是作為控件名稱一部分的標識符。 然后通過選項卡中的控件來處理每個 DataGridView,可能是這樣的:

foreach (Control thisControl in myTabContols)
    if (thisControl.GetType() == typeof(DataGridView))
       // Parse your DataGridView's rows here

其中this.Controls是你的窗體的控件集合( this是指你的父窗體在這種情況下)。

這有幫助嗎? 但我不確定我是否正確理解了您在問題中所問的問題...

我認為你可能想要做的是這樣的:

DataGridView[] formDataGrids = this.Controls.OfType<DataGridView>().ToArray();

這將為您提供表單中所有 DataGridView 的數組。 您可以使用該選項卡的控制列表為單個選項卡執行此操作。 你可以對文本框做同樣的事情,只需用文本框替換數組類型和 OfType() 調用中的類型。

您不能像示例中那樣使用 foreach,因為“in”的右側必須是對特定列表或數組(實現 IEnumerable 的東西)的引用。 但是如果你創建了一個像上面這樣的列表,你可以做這樣的事情:

foreach(DataGridView thisGrid in formDataGrids)
    DoSomething(thisGrid);

或者也將它們鏈接在一起,例如:

foreach(DataGridView thisGrid in this.Controls.OfType<DataGridView>())
    DoSomething(thisGrid);

對於多選項卡處理,您應該已經在設計器中為每個頁面創建了 TabPage 成員。 然后,您可以執行以下操作:

var formDataGrids = new List<DataGridView>();
if (usingTab1)
    formDataGrids.AddRange(tabPage1.Controls.OfType<DataGridView>());
if (usingTab2)
    formDataGrids.AddRange(tabPage2.Controls.OfType<DataGridView>());
if (usingTab3)
    formDataGrids.AddRange(tabPage3.Controls.OfType<DataGridView>());

foreach(var thisGrid in formDataGrids)
    DoSomething(thisGrid);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM