I need a dynamically added label with a click event to add a row to a dynamically added 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.
I have tried adding a datagridview parameter to the event handler but this is not working for me.
Code to create datagridview and link labels.
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:
linkLabel.Tag = datagridView;
Then, in your click event, get the reference:
LinkLabel linkLabel = (LinkLabel)sender;
DataGridView datagridView = (DataGridView)linkLabel.Tag;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.