【发布时间】:2019-09-16 19:42:14
【问题描述】:
我需要一个带有点击事件的动态添加标签,以将一行添加到动态添加的 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.
【问题讨论】:
-
好吧,您已经在私有范围内创建了 datagridview,但它在事件处理程序中不可用。在类级别声明一个变量,然后你就可以使用它了
标签: c# dynamic datagridview controls