简体   繁体   中英

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.

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? Or do i have to pass each property of the datagridview one parameter at a time?

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的属性中。

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.

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