ToolStripMenuItem click event should return a class - c#

I had a DataGrid and a ContextMenuStrip in it. When I click SelectMenuStrip in a row I want the ClickEvent of the context menu to get all data in that row in a databean class and return that databean class, so that I can fill the data in another class-
All was fine I defined event as below
private CustomerDataBean toolStripMenuItem1_Click(object sender, EventArgs e)
{
CustomerDataBean custdatabean = null;
int rowno = tblcustomerdataview.CurrentCellAddress.Y;
custdatabean.Customerpk = int.Parse(tblcustomerdataview.Rows[rowno].Cells[0].Value.ToString());
custdatabean.Contactno = tblcustomerdataview.Rows[rowno].Cells[6].Value.ToString();
custdatabean.Emailid = tblcustomerdataview.Rows[rowno].Cells[7].Value.ToString();
custdatabean.Other = tblcustomerdataview.Rows[rowno].Cells[8].Value.ToString();
return custdatabean;
}
but in designer.cs I am getting an error in line:
this.toolStripMenuItem1.Click += new System.EventHandler(this.toolStripMenuItem1_Click);
The error is:
Error 1:
'WindowsFormsApplication3.CustomerDataBean WindowsFormsApplication3.CustomerSearch.toolStripMenuItem1_Click(object, System.EventArgs)' has the wrong return type D:\WindowsFormsApplication3\WindowsFormsApplication3\Merchandising\customerSearch.Designer.cs 83 46 NFTRANS
Where have I done something wrong?
Let me explain the situation
I had a jobcodeform where user should input the customercode in combobox if he forget customercode he can use a buton to go to another form called customersearch where there is a datagrid table with a context menustrip which when clicked gets the whole details of the selected row in a customerdatabean and return that back to the first jobcodeform

Your code doesn't make a lot of sense. Click events don't return anything (except void), they really just run a procedure.
Your quick fix is to match the signature of the handler:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
// do something, don't return anything
}
What you need to define is what are you trying to do with your CustomerDataBean object. If you are just trying to add it to a list, then add it to a list:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
CustomerDataBean custdatabean = new CustomerDataBean();
// set properties
myBeans.Add(custdatabean);
}
The code you currently have doesn't even create a CustomerDataBean object. It's null, and then you are trying to update a null object. That isn't going to work.

Ask yourself where should your click event return the object to?
What code will process that bean?
The others have explained what is wrong with your click event.
Here's one possible method:
Have your click event call a separate method to process the bean. Something like this, perhaps:
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{
CustomerDataBean custdatabean = null;
int rowno = tblcustomerdataview.CurrentCellAddress.Y;
custdatabean.Customerpk = int.Parse(tblcustomerdataview.Rows[rowno].Cells[0].Value.ToString());
custdatabean.Contactno = tblcustomerdataview.Rows[rowno].Cells[6].Value.ToString();
custdatabean.Emailid = tblcustomerdataview.Rows[rowno].Cells[7].Value.ToString();
custdatabean.Other = tblcustomerdataview.Rows[rowno].Cells[8].Value.ToString();
processBean(custdatabean);
}
private void processBean(CustomerDataBean bean)
{
//Code to process the bean here.
}

ToolStripMenuItem click event handlers need to return void.

Related

ObjectListView cannot cancel item selection BeforeSelect

I converting a standard TreeView to BrightIdeaSoftware.TreeListView
I cannot found how to convert this event
private void LstAgents_BeforeSelect(object sender, TreeViewCancelEventArgs e)
{
// If error save
if (!SaveCurrentValues())
// Keep active selection
e.Cancel = true;
}
How to simply cancel the user action if something was wrong with TreeListView
Thanks ...
If your goal is to prevent the user changing the selected item when there is a validation problem with it then you can use the SelectedIndexChanged event. From a usability point of view it's a bit of a disaster though. You might want to instead highlight the row in red or throw up an error dialog and revert the row.
private object oldSelection = null;
void LstAgents_SelectedIndexChanged(object sender, EventArgs e)
{
if(oldSelection != null && true/* some condition*/)
LstAgents.SelectedObject = oldSelection;
oldSelection = LstAgents.SelectedObject;
}

can't able to add value to textbox

I have a datacontrol.cs(UserControl), which is contain textbox1 and codebehind window having a method with parameter of currentvalue
public void bindvalue(float currentvalue)
{
textbox1.Clear();
textbox1.Text = currentvalue.ToString();
}
I have a Form, Here added the usercontrol in this form and which contains a Button
So when clicking button it pass a currentvalue by the way of method to the datacontrol class like that .
private void button_click(object sender, EventArgs e)
{
float currentvalue = 1500.00f;
datacontrol obj = new datacontrol();
obj.bindvalue(currentvalue);
}
Everything working fine to me. It pass the current value to the usercontrol class and there current value assigned/added to the textbox1.Text = currentvalue.ToString();. It doesn't shows any error . But finally the textbox doesn't shows any value.
I used breakpoint to check the functionality. It gave current value to the textbox. But strange!!!..
I can't predict whats wrong in my code.
Helps appreciated.:)
Your instance of datacontrol with required value (1500.00f) does not exist on your form. You are only delcaring it, passing value and forgetting about it.
If you have already added user control to form and want to call bindvalue method of existing control, you should do the following:
private void button_click(object sender, EventArgs e)
{
float currentvalue = 1500.00f;
this.dataControl1.bindvalue(currentvalue);
}
Note that dataControl1 is the name of your user control on the form, it can be different from dataControl1.
If you want to create new user control and call bindvalue, you should add new instance on the form:
private void button_click(object sender, EventArgs e)
{
float currentvalue = 1500.00f;
datacontrol obj = new datacontrol();
obj.bindvalue(currentvalue);
this.Controls.Add(obj);
}
If it is already dynamically added control on the form, declare a field of Form class, assign new instance of it control, when you want it, and call to it as it shows in the first example.
You need add instance of datacontrol to the form
datacontrol obj = new datacontrol();
obj.bindvalue(currentvalue);
Controls.Add(obj);
You can simply make a call to bindvalue method by using the tagename of your user control in button click event handler.
Suppose the tag name is 'datacontrol', then you should use the following lines of code to achieve your task:
protected void Button1_Click(object sender, EventArgs e)
{
float myvalue = 150.50f;
datacontrol1.BindValue(myvalue);
}
Regards, Aamir ( .Net developer)
Please marks this thread as answer if it solved what were looking for... thanks

Generic Async Completed method

I have a silverlight page with a listbox and a combobox...
Based on what the user clicks in the list box, I want to populate the dropdownbox. The completed event is the same for each item in the list box (items include "BaseTypes", "Bays", "Face", etc)
How can I make the completed method generic so I don't have to have one for each call?
private void lstEdits_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ServiceCylinderClient obj = new ServiceCylinderClient();
obj.GetBaysCompleted += new EventHandler<GetBaysCompletedEventArgs>(GetBaysCompleted(this, baysEventArgs));
string selectedItem = lstEdits.SelectedItem as string;
switch selectedItem
{
case "BaseTypes":
obj.GetBaseTypesCompleted += new EventHandler<GetBaseTypesCompletedEventArgs>(GetBaysCompleted(this, baysEventArgs));
obj.getGetBaseTypesAsync();
break;
case "Bays":
obj.GetBaysCompleted += new EventHandler<GetBaysCompletedEventArgs>(GetBaysCompleted(this, baysEventArgs));
obj.getGetBaysAsync();
break;
}
}
As it stands now, I will have to have a "completed method" for each call, but since they would all do the same thing (just set the list box items source)..i'd like to make it generic to simplify things.
void GetBaseTypesCompleted(object sender, getBaseTypesCompletedEventArgs e)
{
lstEdits.ItemsSource = e.Result;
}
void GetBaysCompleted(object sender, getBaysCompletedEventArgs e)
{
lstEdits.ItemsSource = e.Result;
}
Thanks in advance!
I believe you would need to use reflection to read the 'Result' property off the 'CompletedEventArgs' as they do not all come from a base type that exposes 'Result'.
You should be able to do something like the following:
lstEdits.ItemsSource = (IEnumerable)e.GetType().GetProperty("Result").GetValue(e, null);
I think it dont have easy solution for this problem,because every completedmethod has different EventArgs for different result.

how to generate a SelectionRangeChanged Event Programatically ChartControl WinForms

want to create a selectionRangeChanged event programatically not really getting how to do it
private void btn_10D_Click(object sender, EventArgs e)
{
double varRange = 10;
double var_Sel1 = DatesX[0].ToOADate();
Chart1.ChartAreas["ChartArea1"].CursorX.IsUserEnabled = true;
Chart1.ChartAreas["ChartArea1"].CursorX.IsUserSelectionEnabled = true;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionColor = Color.LightGray;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionStart = var_Sel1;
Chart1.ChartAreas["ChartArea1"].CursorX.SelectionEnd = varRange + var_Sel1;
Chart1.ChartAreas["ChartArea1"].CursorX.Position = varRange + var_Sel1;
Chart1.SelectionRangeChanged += new EventHandler<CursorEventArgs>(Chart1_SelectionRangeChanged);
}
void Chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
throw new NotImplementedException();
}
thank you
For all events in C# is true that if class creator did not make extra effort to allow event firing form outside of class it is impossible to fire them.
According to MSDN
Chart.SelectionRangeChanged event Occurs when the selection start position or end position is changed.
But from my tests I can see that it is fired only if it is changed by user not program.
If I understand your intention correctly you want to handle those small buttons under your chart and btn_10D_Click method is a click handler for one of them. Try to move this line
Chart1.SelectionRangeChanged += new EventHandler<CursorEventArgs>(Chart1_SelectionRangeChanged);
to your constructor and ensure it is called once (remove it form other handlers). This will ensure your code is executed when user changes selection. If you want to execute same code for your button you should simply extract handler contents to method and call it form button click handler.
void Chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
DoSomething(/*some arguments if you need them*/);
}
private void btn_10D_Click(object sender, EventArgs e)
{
\\your code
DoSomething();
}

2 events calling each other

I was wondering about this problem for a while, but couldn't really come up with a solution. I have 2 different event handlers calling each other recursively. As soon as event A is fired, it triggers event B which triggers event A again and so on...
Basically I want to be able to select text in a RichTextBox and show the corresponding font size in a combo box. When I choose a different font size from the ComboBox, I want it's value to be applied to the selected text.
The 2 events are:
1) The selection changed event of text inside a RichTextBox:
private void MyRTB_SelectionChanged(object sender, RoutedEventArgs e)
{
//Get the font size of selected text and select the concurrent size from the ComboBox.
}
2) The selected index changed event of a Combobox:
private void CmbFont_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Apply the chosen font size to the currently selected text of the RichTextBox.
}
What would be the best solution to make sure they each only "do their thing" and do not fire the other event in doing so?
Sometimes changing a property of a control in code fires an event unintentionally. Changing the data source of a ListBox or a ComboBox will fire the SelectedIndexChanged event, for example. Use a flag to handle this case
private bool _loading;
...
_loading = true;
// Fill the ComboBox or ListView here
_loading = false;
In the event handler do this
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (_loading) return;
...
}
Refactor your code so that A calls DoSomethingA() and B calls DoSomethingB(). This way, if you want A to do the functionality of B you can just call DoSomethingB() and not have any recursive calls.
Just use a bool (maybe called dontFireA) and set it in A just before calling B
notifying properties (used in order to enable binding from WPF to non-WPF properies) use this technique:
public object MyProperty
{
get
{
return myField;
}
set
{
if (value != myField)
{
myField = value;
NotifyProperyChanged("MyProperty"); // raise event
}
}
}
The if (value != myField) condition prevents infinite recursion (stackoverflowexception).
In some cases (e.g. floating point numbers and inaccurate value transfers) if (Math.Abs(value - myField) > someConstant) is used instead to break the recursion.
Could you apply a similar technique to your problem?
If both events are on the same object or the owners have references to each other, you could also store a flag on each e.g.
private void OnEvent()
{
DoSomething();
}
private void DoSomething()
{
this.IsBusy = true;
// do work
// raise event
if (!other.IsBusy)
RaiseEvent();
}
I am going to make the educated guess that you are not raising Event A or Event B yourself; let's say Event A is the TextBox1.TextChanged event and Event B is the TextBox2.TextChanged event, and they have handlers like:
public void Textbox1_TextChanged(object sender, EventArgs e)
{
...
TextBox2.Text = someString;
}
public void Textbox2_TextChanged(object sender, EventArgs e)
{
...
TextBox1.Text = someOtherString;
}
In this case, the handlers are each going to raise the other textbox's TextChanged event by virtue of changing the text, leading to infinite recursion.
The first thing you can do, if you want both to run once and once only, is to mark that they're already running (changing the text of the other textbox results in that textbox's event handler running within the same call stack:
public void Textbox1_TextChanged(object sender, EventArgs e)
{
if(handler1Running) return; //the second time through we exit immediately
handler1Running = true;
...
TextBox2.Text = "Something"; //the other event handler is invoked immediately
handler1Running = false;
}
public void Textbox2_TextChanged(object sender, EventArgs e)
{
if(handler2Running) return; //the second time through we exit immediately
handler2Running = true;
...
TextBox1.Text = "Something Else"; //the other event handler is invoked immediately
handler2Running = false;
}
Now, the deepest it will go is three levels; 1's handler invokes 2's handler which invokes 1's handler again, which sees that 1's handler is already running and quits before doing anything that would deepen the recursion. Same thing if you start by changing TextBox2.
The other thing you can do is make sure you aren't trying to set the textbox to the same value that's already there. Changing from one string reference to another, even if both references are the same string value, will fire the TextChanged event. If the recursion must continue naturally but will reach a steady state, this is actually the first thing to try:
public void Textbox1_TextChanged(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
... //build string
//now, even though the builder's ToString will produce a different reference,
//we're making sure we don't unnecessarily change the text.
if(builder.ToString != TextBox2.Text)
TextBox2.Text = builder.ToString();
}
public void Textbox2_TextChanged(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
... //build string
//now, even though the builder's ToString will produce a different reference,
//we're making sure we don't unnecessarily change the text.
if(builder.ToString != TextBox1.Text)
TextBox1.Text = builder.ToString();
}

Categories

Resources