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);
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();
.............
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With