Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to avoid the repeated code to increase the efficiency

I have a DataGrid view1 and a ListView and when ever I select the list view item(I am passing the ListView item into the query and populating the DataGrid view according that item)

I have wrote some 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 have done it like above ... I think this is not an efficient way to do the coding. and this code consisits of a lot of repeated lines, is there any way to refractor this code to a small bunch of code ...... in order improve the efficiency?

Any ideas and sample snippets for increasing code efficiency would be helpful to me ...

Many thanks in advance....

I am using c# and writting WinForms applications.....

like image 470
Glory Raj Avatar asked Aug 29 '11 11:08

Glory Raj


1 Answers

You could save a delegate into the listview item. And call it when the encapsulating item gets selected. For example you would fill your listbox like this:

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

Now, when this item gets selected, you execute the method like so:

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: ! have not tested this code, but something along those lines should work and you don't have to write the If-statement, you only have to construct the items correctly.

Also note that this may be a bit hard to read for someone new to this code.

like image 178
Daniel Rosendorf Avatar answered Nov 01 '22 15:11

Daniel Rosendorf