Share via

Avoid code duplication

Honey singh 20 Reputation points
2023-10-12T14:38:28.6+00:00

Hi , i have a multiple datagridview's in my same project and they all have the same properties .

 DataGridview1.RowHeadersVisible = false;
            DataGridview1.CellBorderStyle = DataGridViewCellBorderStyle.None;
            DataGridview1.ScrollBars = ScrollBars.None;
            DataGridview1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            DataGridview1.MultiSelect = false;
            DataGridview1.AllowUserToResizeColumns = false;


 DataGridview2.RowHeadersVisible = false;    
  DataGridview2.CellBorderStyle = DataGridViewCellBorderStyle.None;            DataGridview2.ScrollBars = ScrollBars.None;          
  DataGridview2.SelectionMode = DataGridViewSelectionMode.FullRowSelect;            DataGridview2.MultiSelect = false;     
       DataGridview2.AllowUserToResizeColumns = false;

there all total about 20 datagridview's with different events but the above would remain same in all of them . So how do i avoid duplication .

Developer technologies | Windows Forms

Answer accepted by question author

Karen Payne MVP 35,606 Reputation points Volunteer Moderator
2023-10-13T13:57:04.6933333+00:00

An extension method is an option e.g.

public static class DataGridViewExtensions
{
    public static void SetCommon(this DataGridView sender)
    {
        sender.CellBorderStyle = DataGridViewCellBorderStyle.None;
        sender.ScrollBars = ScrollBars.None;
        sender.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        sender.MultiSelect = false;
        sender.AllowUserToResizeColumns = false;
    }
}

Usage

dataGridView1.SetCommon();

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.