[英]Need an event handler to work on a dynamically added control which interacts with another dynamically added control
我需要一個帶有click事件的動態添加的標簽,以將行添加到動態添加的datagridview中。 我知道如何使事件處理程序與動態添加的標簽一起使用,但是我不確定如何使它與datagridview一起使用。
我嘗試將datagridview參數添加到事件處理程序,但這對我不起作用。
創建datagridview和鏈接標簽的代碼。
foreach (DataRow rows in dtbl.Rows)
{
// Create Datagridview
DataGridView datagridview = new DataGridView();
// Create link labels
LinkLabel linkLabel = new LinkLabel();
// Add event handler to the link labels
linkLabel.Click += new EventHandler(this.linkLabel_Click);
this.Controls.Add(datagridview);
this.Controls.Add(linkLabel);
}
// Event handler
private void linkLabel_Click(object sender, EventArgs e)
{
// This doesnt work because "datagridview" doesnt exist, but I just have no idea how to get this to interact with the dynamically created datagridviews.
int rowIndex = datagridview.Rows.Add();
DataGridViewRow row = datagridview.Rows[rowIndex];
row.Cells[0].Value = "5";
datagridview.CurrentCell = row.Cells[0];
}
I expect each link label to add a new row to the datagridview it was created with in the for loop. But I just don't how to code it.
在你foreach
在其中創建循環LinkLabel
和DataGridView
,你可以分配的參考DataGridView
到LinkLabel
-假設你在Windows窗體或WPF這樣做,你可以使用該控件的的Tag
屬性:
linkLabel.Tag = datagridView;
然后,在您的click事件中,獲取參考:
LinkLabel linkLabel = (LinkLabel)sender;
DataGridView datagridView = (DataGridView)linkLabel.Tag;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.