如何通过EventHandler传递变量?

时间:2018-04-16 11:13:47

标签: c# event-handling

我有dataGridView1_CellContentClick检查是否单击了特定单元格。

点击它后会创建一个新的Form

在此表单上有dateTimePickerButton

单击该按钮时,我希望将dateTimePicker的值添加到dataGridView中的正确行和单元格中。

这是我到目前为止所拥有的。

   private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
 if (e.ColumnIndex == dataGridView1.Columns[16].Index && e.RowIndex >= 0)
        {
                int numberRow = Convert.ToInt32(e.RowIndex);
                var form3 = new Form();
                form3.Width = 400;
                form3.Height = 200;
                form3.Text = "How long will you have the item?";
                form3.Show();

                DateTimePicker howLongPick = new DateTimePicker();
                howLongPick.Width = 150;
                howLongPick.Value = DateTime.Today.AddDays(7);
                howLongPick.Location = new Point(100, 50);

                Button addDate = new Button();
                addDate.Location = new Point(135, 100);
                addDate.Text = "OK";

                form3.Controls.Add(addDate);
                form3.Controls.Add(howLongPick);

                CheckoutUntil = howLongPick.Text;

                addDate.Click += new EventHandler(addDateClicked);

                dataGridView1.Rows[numberRow].Cells[4].Value = true;
                newHistoryRow["Action"] = "Checkout";
                sIMSDataSet.Tables["History"].Rows.Add(newHistoryRow);
                historyTableAdapter.Update(sIMSDataSet);
        }
     }

    private void addDateClicked(object sender, EventArgs e, int numberRow)
    {
        dataGridView1.Rows[numberRow].Cells[15].Value = CheckoutUntil;
    }

我想做的是将numberRow传递给addDate.Click += new EventHandler(addDateClicked);

但我似乎无法弄明白该怎么做。

1 个答案:

答案 0 :(得分:2)

简单地避免创建方法addDateClicked,只需这样内联:

int numberRow = Convert.ToInt32(e.RowIndex);

// code commented out

addDate.Click += (s, e2) =>
{
    // you can use `numberRow` in here now.
    dataGridView1.Rows[numberRow].Cells[15].Value = CheckoutUntil;
};
相关问题