简体   繁体   English

需要一个事件处理程序来处理与另一个动态添加的控件交互的动态添加的控件

[英]Need an event handler to work on a dynamically added control which interacts with another dynamically added control

I need a dynamically added label with a click event to add a row to a dynamically added datagridview. 我需要一个带有click事件的动态添加的标签,以将行添加到动态添加的datagridview中。 I know how to get an event handler to work with a dynamically added label but I am not sure how to get it to work with the datagridview as well. 我知道如何使事件处理程序与动态添加的标签一起使用,但是我不确定如何使它与datagridview一起使用。

I have tried adding a datagridview parameter to the event handler but this is not working for me. 我尝试将datagridview参数添加到事件处理程序,但这对我不起作用。

Code to create datagridview and link labels. 创建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.

In your foreach loop where you create the LinkLabel and DataGridView , you can assign a reference of the DataGridView to LinkLabel -- Assuming you are doing this in Windows Form or WPF, you can make use of the control's Tag property: 在你foreach在其中创建循环LinkLabelDataGridView ,你可以分配的参考DataGridViewLinkLabel -假设你在Windows窗体或WPF这样做,你可以使用该控件的的Tag属性:

linkLabel.Tag = datagridView;

Then, in your click event, get the reference: 然后,在您的click事件中,获取参考:

LinkLabel linkLabel = (LinkLabel)sender;
DataGridView datagridView = (DataGridView)linkLabel.Tag;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM