Reduce the number of arguments in function

scottdg

New member
Joined
Jul 10, 2018
Messages
4
Programming Experience
3-5
I want to call a function when double clicking on a DataGridView row that retrieves the data from SQL Server and displays it in the appropriate checkbox, textbox, etc.
The issue is I have a couple dozen columns in the query that need to be displayed. There has to be a better way to do this rather than have 2 dozen arguments in the function. I just don't know what they might be.

I have something similar to this currently.

C#:
        public void GetFac(string ID, CheckBox chk1, CheckBox chk2, TextBox txt1, TextBox txt2.....TextBox txt22)
        {

            SqlConnection myDB= new SqlConnection(connP);
            SqlCommand getLoc = new SqlCommand("MySP", myDB);
            getLoc.CommandType = CommandType.StoredProcedure;
            getLoc.Parameters.AddWithValue("@ID", ID);
            misc.Open();
            SqlDataReader dr = null;
            dr = getFac.ExecuteReader();

            while (dr.Read())
            {
                chk1.Checked = (Convert.ToBoolean(dr["col1"].ToString()));
                chk2.Checked = (Convert.ToBoolean(dr["Col2"].ToString()));
                chk3 = (Convert.ToBoolean(dr["Col3"].ToString()));
                ...
                ...etc
            }
        }
 
Yes there is. Use WPF with MVVM pattern and data binding.

WinForms also has data binding with the UI, but it is more cumbersome than WPFs.

Anyway, the way to reduce the number of controls you pass in, pass them in using a data structure.

Although most people associate DTOs (Data Transfer Objects) and POCOs (Plain Old C# Objects) with database access and/or serialization, you could use them in process as well to reduce the number of parameters in the method signature.

Another alternative is to use a dictionary. Have the key as field name, and the value as a Action that takes a field value.

Or a list of controls you know the explicit order of the controls coming in, but this can be quite fragile. An alternative is for the list to contain structs with essentially the same information as the dictionary above: field name and Action, or field name, type, and control.
 
Where exactly is the code that you have shown us? If it's in the UI then you probably don't need to pass that controls as arguments and if it's in a data access layer then you definitely shouldn't.
 
Back
Top Bottom