简体   繁体   English

从另一个类访问 datagridview

[英]Accessing a datagridview from another class

I have an application that is working, but Im wanting to organise it a bit better by moving some of my methods into their own classes in separate files as currently i have one long mega list of code.我有一个正在运行的应用程序,但我想通过将我的一些方法移动到它们自己的类中的单独文件中来更好地组织它,因为目前我有一个很长的大型代码列表。 This is something i have not tried before.这是我以前没有尝试过的。

I created the separate class in its own file and checked i could access it ok (which I can) but I have found as it uses a datagridview from the main form (that the original method was from) it now no longer can access said datagridview from the new class.我在自己的文件中创建了单独的类并检查了我可以访问它(我可以)但我发现因为它使用主窗体中的 datagridview(原始方法来自)它现在不再可以访问所说的 datagridview来自新班级。

What is the best way to get round this?解决这个问题的最佳方法是什么? Can i bring the whole datagridview in as a parameter to the method and then get access to it?我可以将整个 datagridview 作为方法的参数引入,然后访问它吗? Or do i have to pass each property of the datagridview one parameter at a time?或者我必须一次传递datagridview的每个属性一个参数吗?

The method basically applies formatting to the datagrid as well so it needs to be able to update back to the main form also.该方法基本上也将格式应用于数据网格,因此它也需要能够更新回主表单。

public class GridFormat
    {
        public void applyFormat()
        {
            //Method to Apply formatting to main grid

            int complete = -1;
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                string header = dataGridView1.Columns[i].HeaderText;
                if (header == "Completed" || header == "jlComplete") { complete = i; }
            }

            foreach (DataGridViewRow row in dataGridView1.Rows)
            {

                if ((Convert.ToString(row.Cells[complete].Value) == "True"))
                {
                    row.DefaultCellStyle.ForeColor = Color.Gray;
                }
            }
        }

    }

您可以将数据网格作为参数提供给applyFormat ,或者如果该数据网格特定于您的GridFormat实例,则将其存储在GridFormat的属性中。

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

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