Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Structuring button click methods to avoid code repetition

Tags:

c#

asp.net

I have the following two button click methods that create an array from three TextBoxes, order the values, insert them into a database and then select the values in the same order. The only difference between the two buttons is that one orders the values in ascending order and the other in descending order.

I'm not used to working with C#. Can anybody suggest the best way to structure my code so I'm not repeating it for each button? Normally I'd write a function and have each button pass it arguments. Is that the right way to go here?

Thanks in advance.

Button1

protected void Button1_Click(object sender, EventArgs e)
{
    var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
    var orderedlist = list.OrderBy(x => (x)).ToArray();

...

    SqlCommand cmd = new SqlCommand("Select * from lists order by values asc", conn);

Button2

protected void Button2_Click(object sender, EventArgs e)
{
    var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
    var orderedlist = list.OrderByDescending(x => (x)).ToArray();

...

    SqlCommand cmd = new SqlCommand("Select * from lists order by values desc", conn);
like image 944
user1405195 Avatar asked Feb 25 '13 21:02

user1405195


2 Answers

You could just assign both Button click events to the same handler and use the sender choose what sorting you want.

protected void Button_Click(object sender, EventArgs e)
{
    var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
    var orderedlist = (sender as Button).AccessKey  == "Button1" // or whatever name it is
                      ? list.OrderByDescending(x => (x)).ToArray()
                      : list.OrderBy(x => (x)).ToArray();

    .............
}
like image 150
sa_ddam213 Avatar answered Sep 20 '22 21:09

sa_ddam213


On option would be to create a function, sort:

public list sort(String order)
{
     var list = new string[] { TextBox1.Text, TextBox2.Text, TextBox3.Text };
     var orderedlist = list.OrderByDescending(x => (x)).ToArray();
     ...

     SqlCommand cmd = new SqlCommand("Select * from lists order by values " + order, conn)
     ...
     return SortedList;
}

Call sort("asc") to create the sorted list in ascending order, and sort("desc") to sort in descending order. And no code repetition :)

like image 38
christopher Avatar answered Sep 17 '22 21:09

christopher