How can I combine these two similar methods into one? - c#

The methods below are just inverses of one another. I suspect that I can combine the logic into one method. I prefer to avoid Reflection. Is it possible to combine them and maintain readability?
private void btnAdd_Click(object sender, EventArgs e)
{
LabEntity selectedItem = bindingSource1.Current as LabEntity;
selectedLabsData.Add(selectedItem);
availableLabsData.Remove(selectedItem);
}
private void btnRemove_Click(object sender, EventArgs e)
{
LabEntity selectedItem = bindingSource2.Current as LabEntity;//new binding source
availableLabsData.Add(selectedItem);//called Add instead of remove
selectedLabsData.Remove(selectedItem);//called Remove instead of Add
}

You could factor out the logic into a helper method:
private void ListFixup(object entity, List<Item> addList, List<Item> removeList)
{
LabEntity selectedItem = entity as LabEntity;
// don't forget your error checking here
addList.Add(selectedItem);
removeList.Remove(selectedItem);
}
private void btnAdd_Click(object sender, EventArgs e)
{
ListFixup(bindingSource1.Current, selectedLabsData, availableLabsData);
}
private void btnRemove_Click(object sender, EventArgs e)
{
ListFixup(bindingSource2.Current, availableLabsData, selectedLabsData);
}
I'm not sure this helps readability, but it does reduce code duplication.

private void btnAdd_Click(object sender, EventArgs e)
{
SwapThem( bindingSource1, selectedLabsData, availableLabsData );
}
private void btnRemove_Click(object sender, EventArgs e)
{
SwapThem( bindingSource2, availableLabsData, selectedLabsData );
}
// I just don't know the proper type-cast of the "toAddTo" and "toRemoveFrom" parameters.
private void SwapThem( BindingSource bs, List<yourType> toAddTo, List<yourType> toRemoveFrom )
{
LabEntity selectedItem = bs.Current as LabEntity;
toAddTo.Add(selectedItem);
toRemoveFrom.Remove(selectedItem);
}

There isn't any way to refactor the two methods that wouldn't result in significantly reducing the readability of the code, you can see this in some of the other answers posted. This is a case where the level of code duplication is acceptable for the sake of readability.

Add a tag to the sender?
private void btnClick(object sender, EventArgs e)
{
Button *myButton = (Button)sender;
if (myButton.tag == 1){
LabEntity selectedItem = bindingSource1.Current as LabEntity;
selectedLabsData.Add(selectedItem);
availableLabsData.Remove(selectedItem);
}
else {
LabEntity selectedItem = bindingSource2.Current as LabEntity;//new binding source
availableLabsData.Add(selectedItem);//called Add instead of remove
selectedLabsData.Remove(selectedItem);//called Remove instead of Add
}
}
I havn't checked this for compiler errors, It is just an example.

Have both buttons link to a single event handler. The handler could then look something like this: (excuse the multiple checks on the buttons as I don't know what type to declare holders for 'availableLabsData' and 'selectedLabsData' as):
private void btnClick(object sender, EventArgs e)
{
var bindingSource = (sender == btnRemove) ? bindingSource2 : bindingSource1;
var selectedItem = source.Current as LabEntity;
if(sender == btnRemove)
{
availableLabsData.Add(selectedItem);
selectedLabsData.Remove(selectedItem);
}
else if(sender == btnAdd)
{
availableLabsData.Remove(selectedItem);
selectedLabsData.Add(selectedItem);
}
}

Everyone's right about not going overboard at the expense of making the code less readable
The only thought I have is ...
From just the code posted but it looks like selectedLabsData and availableLabsData are tightly intertwined so I wouldn't put logic related to them in your event handlers. Put the logic in different methods (preferably a different class) so that you don't ever accidentally update one without updating the other. This has the benefit of making the methods in question simpler and more "readable".
private void LabsDataAdded(LabEntity value)
{
selectedLabsData.Add(value);
availableLabsData.Remove(value);
}
private void LabsDataRemoved(LabEntity value)
{
availableLabsData.Add(value);
selectedLabsData.Remove(value);
}
then the methods would just be:
private void btnAdd_Click(object sender, EventArgs e)
{
LabsDataAdded(bindingSource1.Current as LabEntity);
}
private void btnRemove_Click(object sender, EventArgs e)
{
LabsDataRemoved(bindingSource2.Current as LabEntity);
}
Even better, you could use lambda expressions to make the code even more succinct:
btnAdd.Clicked += (sender, e) => LabsDataAdded(bindingSource1.Current as LabEntity);
btnAdd.Clicked += (sender, e) => LabsDataRemoved(bindingSource1.Current as LabEntity);

Something like this:
private void btnAdd_Click(object sender, EventArgs e)
{
LabEntity selectedItem = bindingSource1.Current as LabEntity;
RemoveItemFromList(selectedItem);
}
private void btnRemove_Click(object sender, EventArgs e)
{
LabEntity selectedItem = bindingSource2.Current as LabEntity;//new binding source
RemoveItemFromList(selectedItem);
}
private void RemoveItemFromList(LabEntity ent)
{
selectedLabsData.Add(ent);
availableLabsData.Remove(ent);
}

Related

How to perform Click-Event on a hidden button

In my C# form I have two buttons
button1.Hide()
private void button2_Click(object sender, EventArgs e)
{
button1.PerformClick();
}
The button1 is hidden at form loading, I want the logic behind button1 to be perfomed when it's hidden too.
Just let the function outside become another function, then you can call function although you hidden the button1.
private void button1(object sender, EventArgs e)
{
_button1();
}
private void button2(object sender, EventArgs e)
{
_button1();
}
//Here is the function
void _button1()
{
...
}
If your Button is hidden, it seems that you need the functionality behind not or just in special cases. Keeping functionality out of events is often a simple solution to avoid problems in the future.
private void btn_Reload_Click(object sender, EventArgs e)
{
// reload here - maybe you reload all your employees from a datasource
}
private void btn_Reload_With_Calculation_Click(object sender, EventArgs e)
{
// you can use functionality here from a another button and call the
btn_Reload_Click(this, EventArgs.Empty); // DON'T DO THIS IN MY OPINION
// ....
}
Maybe this solution is better even if you need the functionality at other workflows.
private void btn_Reload_Click(object sender, EventArgs e)
{
Reload();
}
private void btn_Reload_With_Calculation_Click(object sender, EventArgs e)
{
Reload();
Calculate();
}
void Reload() { }
void Calculate() { }

More effective way to implement big amount of events

I am new to Visual C#, I am implementing a WPF application but I want to use a more effective way for events since I have another method for every single tool.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
KeyUp(textBox1, e);
}
private void textBox2_KeyUp(object sender, KeyEventArgs e)
{
KeyUp(textBox2, e);
}
private void textBox3_KeyUp(object sender, KeyEventArgs e)
{
KeyUp(textBox3, e);
}
private void textBox4_KeyUp(object sender, KeyEventArgs e)
{
KeyUp(textBox4, e);
}
private void textBox5_KeyUp(object sender, KeyEventArgs e)
{
KeyUp(textBox5, e);
}
private void TextChanged(int x, TextBox txt)
{
int i = dataGridView1.CurrentCell.RowIndex;
dataGridView1.Rows[i].Cells[x].Value = txt.Text;
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
TextChanged(1, textBox2);
}
private void textBox3_TextChanged_1(object sender, EventArgs e)
{
TextChanged(2, textBox3);
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
TextChanged(3, textBox4);
}
private void textBox5_TextChanged_1(object sender, EventArgs e)
{
TextChanged(4, textBox5);
}
and so on. Instead of occupying so much lines, I am looking for a shorter way for all these events. Seems like I have to use Mapping, but I could not manage it. Any help would be highly appreciated
You could use one event handler for all textbox keyup events as follows;
private void textBox_KeyUp(object sender, KeyEventArgs e)
{
KeyUp((TextBox)sender, e);
}
you could use same kind of logic for rest of the events once you get the idea.
You need two event handlers (they are reusable you know)
First:
private void OnTextBoxKeyUp(object sender, KeyEventArgs e)
{
KeyUp((Textbox)sender, e);
}
Second:
private void OnTextChanged(object sender, EventArgs e)
{
var textBox = (Textbox)sender;
var i = dataGridView1.CurrentCell.RowIndex;
var x = (int)textbox.Tag
dataGridView1.Rows[i].Cells[x].Value = textBox.Text;
}
For the second part you need to set the FrameworkElement.Tag property in code like so:
<Textbox Tag="1" />
For completeness sake here is the xaml part for your textboxes:
<Textbox x:Name="textBox1" Tag="1" TextChanged="OnTextChanged" KeyUp="OnTextBoxKeyUp"/>
<Textbox x:Name="textBox2" Tag="2" TextChanged="OnTextChanged" KeyUp="OnTextBoxKeyUp"/>
And so on. Note that x:Name part is probably not needed as you don't need to reference the textboxes by name in the code behind with this solution.
First give your textboxes name as
TextBox1, TextBox2, TextBox3 ... and add a common textBoxAll_TextChanged event handler for all textboxes.
Then execute the below code :
private void textBoxAll_TextChanged(object sender, EventArgs e)
{
var tb = sender as TextBox;
int x = int.Parse(tb.Name.Substring(7,1)) - 1;
TextChanged(x, tb);
}

How to execute the same code for different events

I have to work with touch monitors and sometimes with mouse and normal monitors.
So for drag and drop the for the first would be
private void lvAllowedPPtab2_StylusButtonDown(object sender, StylusButtonEventArgs e)
and for the second
private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
after that I have to execute the same code using sender and e.
I didn't get to make a common code routine.
The two event are similar and both have the GetPosition event.
I might have taken the wrong road but I have tought to something like:
Type eventType;
if (_e is StylusButtonEventArgs)
eventType = typeof (StylusButtonEventArgs);
else
eventType = typeof(MouseEventArgs);
but then I don't know how to cast e to event type.
Thank you
you can call them both with that
private void listView_StylusButtonDown(object sender, StylusButtonEventArgs e) { CommonCode(sender, e); }
private void listView_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e) { CommonCode(sender, e); }
and then tell inside common code
private void CommonCode(object sender, object _e)
{
//Sender is common
ListView parent = (ListView)sender;
string strListViewButtonName = (sender as ListView).Name;
if (_e is StylusButtonEventArgs)
... (_e as StylusButtonEventArgs).GetPosition(parent));
else
... (_e as MouseEventArgs).GetPosition(parent));
}
Better implementation (thanks to Eli Arbel):
private void listView_StylusButtonDown(object sender, StylusButtonEventArgs e) { CommonCode(sender, e.GetPosition((ListView)sender)); }
private void listView_PreviewMouseLeftButtonDown(object sender, MouseEventArgs e) { CommonCode(sender, e.GetPosition((ListView)sender)); }
private void CommonCode(object sender, Point p)
{
//Sender is common
ListView parent = (ListView)sender;
string strListViewButtonName = (sender as ListView).Name;
//you don't need getPosition since P is known
}

How to go from one "private void" to other "private void"?

how can i go from private void turnon to private void turnoff ? I want only know how to go from one void to other. I know i can just make from these two a one private void but i don't want it
private void turnon(object sender, EventArgs e)
{
button2.Visible = true
}
private void turnoff(object sender, EventArgs e)
{
button3.Visible = false
}
If you're wanting it to be visible in one event and visible in another, why not use one method like so:
private void SwitchState(object sender, EventArgs e)
{
button3.Visible = !button3.Visible;
}
On reading your comments I guess you want to add this line in at the end of your turnon event:
turnoff(sender, e);
Do you want a toggle? If so, you could use the following code.
private void toggle(object sender, EventArgs e)
{
button2.Visible = !button2.Visible;
}
Hi I want to make toggle button, So that it shows/hides the content by clicking that searchButton
Here is my code,
private boolean visible;
protected Button SearchButton;
private void Toggle(){
if(visible=false){
DishButton.setVisibility(View.INVISIBLE);
SpoonButton.setVisibility(View.INVISIBLE);
cupButton.setVisibility(View.INVISIBLE);
FridgeButton.setVisibility(View.INVISIBLE);
}
else {
DishButton.setVisibility(View.VISIBLE);
SpoonButton.setVisibility(View.VISIBLE);
cupButton.setVisibility(View.VISIBLE);
FridgeButton.setVisibility(View.VISIBLE);
visible=true;
}
}

calling a event handler within another event handler?

Here is the short sample code:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
button1_Click(object sender, EventArgs e); //can I call button1 event handler?
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(txtbox1.Text);
}
I wonder if it would be okay to code in the above way?
You can do that - although the code you provide can't be compiled. It should look like this:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
button1_Click(sender, e);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(txtbox1.Text);
}
But for best practice and code readability, you're probably better off doing this, especially as you are not making use of sender and e:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
ShowMessageBox();
}
private void button1_Click(object sender, EventArgs e)
{
ShowMessageBox();
}
private void ShowMessageBox()
{
MessageBox.Show(txtbox1.Text);
}
Yes you can do that; an event handler is just another method.
However it might be worth creating a new method that shows the message box, and having both Click event handlers call that:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
ShowTextboxMessage();
}
private void button1_Click(object sender, EventArgs e)
{
ShowTextboxMessage();
}
private void ShowTextboxMessage()
{
MessageBox.Show(txtbox1.Text);
}
An event handler is nothing more than a method, so you can call it like any other.

Categories

Resources