Avoiding re-code to increase efficiency

I have a DataGrid view1 and ListView , and when I select a list item (I pass the ListView element to the request and populate the DataGrid view with that element)

I wrote code like this ....

  private void listview_selectedindexchanged(object sender event args) { if (listview.SelectedItems.Count > 0 && listview.SelectedItems[0].Group.Name == "abc") { if(lstview.SelectedItems[0].Text.ToString() == "sfs") { method1(); } else { // datagrid view1 binding blah..... } } if (lstview.SelectedItems.Count > 0 && lstview.SelectedItems[0].Group.Name == "def") { if(lstview.SelectedItems[0].Text.ToString() == "xyz") { method 1(); } if(lstview.SelectedItems[0].Text.ToString() == "ghi") { method 2(a,b); } if(lstview.SelectedItems[0].Text.ToString() == "jkl") { method 2(c,d); } if(lstview.SelectedItems[0].Text.ToString() == "mno") { method 3(); } } } private void method 1() { // datagrid view1 binding blahh } private void method 2(e,g) { // datagrid view1 binding blah....blah.. } private void method 3() { // datagrid view1 binding } 

I did this as described above ... I think this is not an efficient way of coding. and this code contains many repeating lines, is there any way to refract this code to a small group of code ...... in order to increase efficiency?

Any ideas and examples of snippets to improve code efficiency would be helpful to me ...

Thank you very much in advance....

I am using C # and calling WinForms applications .....

+6
source share
2 answers

You can save the delegate in the listview element. And name it when the encapsulation element is selected. For example, you fill out your list as follows:

 ListViewItem item = new ListViewItem("abc"); item.Tag = new Delegate(method1); lstview.Items.Add(item); 

Now that this item is selected, you will execute the method as follows:

 private void listview_selectedindexchanged(object sender event args) { ((Delegate)lstview.SelectedItems[0].Tag)(); // this will execute method1 if the item with text "abc" gets selected } 

NOTE:! We have not tested this code, but something in this direction should work, and you do not need to write an If statement, you only need to create the elements correctly.

Also note that it can be a little difficult to read for someone new to this code.

+4
source

You can easily extract a new method to perform "datagrid view1 view binding". This method is then called from all methods that must bind.

0
source

Source: https://habr.com/ru/post/896120/


All Articles