传递变量以及事件

时间:2017-02-09 21:23:38

标签: c#

我需要将maxColumns的值传递给将被其他项重复使用的方法。如何在这种情况下传递maxColumns

public partial class ValResults : Form
{
    public ValResults()
    {
        InitializeComponent();
        this.Table1Requirements();

    }

    private void Table1Requirements()
    {
        int maxColumns = 6;
        this.table1LayoutPanelPrime.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPaint);

    }

   void tableLayoutPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
        for (int i = 0; i < maxColumns; i++)
        {
            if (e.Row == 0 && e.Column == i)
            {
                Graphics g = e.Graphics;
                Rectangle r = e.CellBounds;
                g.FillRectangle(Brushes.LightGray, r);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

如果它在同一个类中,只需在类级别定义变量。

 private int _maxColumns;
 public ValResults()
    {
        InitializeComponent();
        this.Table1Requirements();
        SetColumnCount(); 
    }

private void SetColumnCount(){
    _maxColumns= 6;
}

void tableLayoutPaint(object sender, TableLayoutCellPaintEventArgs e)
    {
        for (int i = 0; i < _maxColumns; i++)
        {
            if (e.Row == 0 && e.Column == i)
        {
                Graphics g = e.Graphics;
                Rectangle r = e.CellBounds;
                g.FillRectangle(Brushes.LightGray, r);
        }
        }
    }

答案 1 :(得分:0)

你基本上可以使用lambdas构建一个函数...

private void Table1Requirements()
    {
        int maxColumns = 6;
        this.table1LayoutPanelPrime.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPaint(maxColumns));

    }

   Action<object,TableLayoutCellPaintEventArgs> tableLayoutPaint(int columns)
    return (sender, e) => 
    {
        for (int i = 0; i < columns; i++)
        {
            if (e.Row == 0 && e.Column == i)
            {
                Graphics g = e.Graphics;
                Rectangle r = e.CellBounds;
                g.FillRectangle(Brushes.LightGray, r);
            }
        }
    }

通过这种方式,您可以使用不同的最大列设置生成不同的事件句柄