[英]C# UserControl - Get property value each control inside UserControl on Click event
我有一個這樣的自定義UserControl(它的名稱是TP1CustomListView ):
我使用了具有兩列的TableLayoutPanel來保存圖片(在第一列上)和另一張TableLayoutPanel(在第二列上)。 第二列中的TableLayoutPanel具有3行以容納3個TextBox。
我在UserControl中為PictureBox編寫了一個Click事件,如下所示:
//events
public new event EventHandler Click
{
add { picbox.Click += value; }
remove { picbox.Click -= value; }
}
在Form1中,我有10個UserControl,就像我貼在主題頂部的圖片一樣。 我在Form1中為所有UserControl編寫了一個Click事件。 我試圖將每個UserControl的發送者強制轉換為Click,以在該UserControl中獲得3 TextBox的3個值。 但是我得到的結果是“ NULL”。
這是我的Click事件代碼:
public Form1()
{
InitializeComponent();
foreach (Control c in this.Controls)
{
TP1CustomListView ctLV = c as TP1CustomListView;
if (ctLV != null)
{
ctLV.Click += ctLV_Click;
}
}
}
void ctLV_Click(object sender, EventArgs e)
{
TP1CustomListView customView = sender as TP1CustomListView;
if(customView!=null)
{
MessageBox.Show(customView.subtbTitle.Text + customView.subtbContent.Text + customView.subtbFooter.Text);
}
}
這是我的TP1CustomListView(UserControl)中的構造函數和子控件:
//sub controls
public PictureBox subPicbox;
public TextBox subtbTitle;
public TextBox subtbContent;
public TextBox subtbFooter;
public TP1CustomListView()
{
InitializeComponent();
subtbTitle = txtTitle;
subtbContent = txtContent;
subtbFooter = txtFooter;
subPicbox = picbox;
tableLayoutPanel1.Dock = DockStyle.Fill;
}
希望每個人都能給我一些建議或解決我的問題的方法。 謝謝!
您應該在用戶控件內處理PictureBox的click事件,並在發生該事件時從UserControl引發click事件。
在用戶控件內,您應該具有以下內容:
picturebox.Click += picturebox_click;
private void picturebox_click(object sender, EventArgs e)
{
var handler = this.Click;
if(handler != null)
{
handler(this, e);
}
}
這樣,您在圖片框上的單擊將觸發對用戶控件的單擊,而該單擊是您在表單中實際聽到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.