I am making a program that should just continue if 2 conditions are given.
The first one, 2 TextBoxs have the same word in and a Button was clicked, which opens a new Form. Now I have the event for the "complete" button.
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == textBox3.Text && ???)
{
StreamWriter myWriter = File.CreateText(#"c:\Program Files\text.txt");
myWriter.WriteLine(textBox1.Text);
myWriter.WriteLine(textBox2.Text);
}
]
My problem is, I can't find a method that gives something like `button1.Clicked or something similar.
I hope someone can help me here..
Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.
private bool button1WasClicked = false;
private void button1_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox2.Text == textBox3.Text && button1WasClicked)
{
StreamWriter myWriter = File.CreateText(#"c:\Program Files\text.txt");
myWriter.WriteLine(textBox1.Text);
myWriter.WriteLine(textBox2.Text);
button1WasClicked = false;
}
}
These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.
if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
//Do not reload the gridview.
}
else
{
reload my gridview.
}
SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked
button1, button2 and button3 have same even handler
private void button1_Click(Object sender, EventArgs e)
{
Button btnSender = (Button)sender;
if (btnSender == button1 || btnSender == button2)
{
//some code here
}
else if (btnSender == button3)
//some code here
}
i am very new to this website. I am an undergraduate student, doing my Bachelor Of Computer Application.
I am doing a simple program in Visual Studio using C# and I came across the same problem, how to check whether a button is clicked?
I wanted to do this,
if(-button1 is clicked-) then
{
this should happen;
}
if(-button2 is clicked-) then
{
this should happen;
}
I didn't know what to do, so I tried searching for the solution in the internet. I got many solutions which didn't help me. So, I tried something on my own and did this,
int i;
private void button1_Click(object sender, EventArgs e)
{
i = 1;
label3.Text = "Principle";
label4.Text = "Rate";
label5.Text = "Time";
label6.Text = "Simple Interest";
}
private void button2_Click(object sender, EventArgs e)
{
i = 2;
label3.Text = "SI";
label4.Text = "Rate";
label5.Text = "Time";
label6.Text = "Principle";
}
private void button5_Click(object sender, EventArgs e)
{
try
{
if (i == 1)
{
si = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text)) / 100;
textBox4.Text = Convert.ToString(si);
}
if (i == 2)
{
p = (Convert.ToInt32(textBox1.Text) * 100) / (Convert.ToInt32(textBox2.Text) * Convert.ToInt32(textBox3.Text));
textBox4.Text = Convert.ToString(p);
}
I declared a variable "i" and assigned it with different values in different buttons and checked the value of i in the if function.
It worked. Give your suggestions if any. Thank you.
Related
Could you tell me how to put together the many button event.
Writing all the many button event is bad Maintainability.
So I want to turn many button event into one method.
Like this...
Before
private void button1_Click(object sender, EventArgs e)
{
//button1 event
}
private void button2_Click(object sender, EventArgs e)
{
//button2event
}
private void buttonN_Click(object sender, EventArgs e)
{
//buttonNevent
}
After
private void buttonClickEvent(object sender, EventArgs e)
{
Button btn = (Button)sender;
int index = int.Parse(btn.Name.Replace("button", ""));
if(index==1)
{
//button1 event
}
if(index==2)
{
//button2 event
}
}
In ASP.NET Web Forms I've solved this situation like this.
Define a general hidden button (this will be the trigger for all). You should define it "hidden" using the styles.
<asp:Button ID="btnPrintPdf" runat="server" Style="display: none" OnClick="btnPrint_Click" />
For the all other buttons "redirect" the click on the client side to the general one like this:
btnPrintPlan.OnClientClick = ClientScript.GetPostBackClientHyperlink(btnPrintPdf, itemData.ClientIw.ID.ToString() + "|" + ((int)PrintDocs.NextStepsPlan).ToString()) + ";return false;";
btnPrintNetWorth.OnClientClick = ClientScript.GetPostBackClientHyperlink(btnPrintPdf, itemData.ClientIw.ID.ToString() + "|" + ((int)PrintDocs.NetWorth).ToString()) + ";return false;";
As you can see, I use a Enum to define what I want to print by clicking different buttons.
The last part is to define the "general" button logic:
protected void btnPrint_Click(object sender, EventArgs e)
{
string sVal = Request.Params["__EVENTARGUMENT"];
if (string.IsNullOrEmpty(sVal))
return;
string[] tks = sVal.Split('|');
if (tks.Length != 2)
return;
string sOrderId = tks[0];
string sPrintType = tks[1];
int orderId = 0;
int iPrintType = 0;
if (!int.TryParse(sOrderId, out orderId) || !int.TryParse(sPrintType, out iPrintType))
return;
string sPdf = null;
if (iPrintType == (int)PrintDocs.NextStepsPlan)
{
....
}//endif
if (iPrintType == (int)PrintDocs.NetWorth)
{
....
}//endif
You could try something like this. Dictionary would be better than if's if you have hundreds of buttons.
private Dictionary<string, Action<object, EventArgs>> buttonEventMap = new Dictionary<string, Action<object, EventArgs>>();
private void setup()
{
buttonEventMap["button1"] = (object sender, EventArgs e)=>{Console.WriteLine("Button 1 Clicked");};
// etc....
}
private void buttonClickEvent(object sender, EventArgs e)
{
Button btn = (Button)sender;
if( buttonEventMap.ContainsKey(btn.Name))
buttonEventMap[btn.Name](sender, e);
}
Although this still is't much different from just implementing each individual ButtonClickEvent.
Here's what H have so far:
private void button1_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.ai_yori_aoshi_5370;
}
private void button2_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.AiYoriAoshi_feature;
}
private void button3_Click(object sender, EventArgs e)
{
audio.Stop();
if (button1.Enabled == true)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-guide");
if (button2.Enabled == true)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-enishi-guide");
}
}
}
this is only my test so far but what i want to do is change what button 3 does, i.e. if button 1 is clicked button three will open webpage 1, if button2 is clicked button 3 will open webpage 2, button 3's image will change depending, but what im finding with what i have done so far is that it opens BOTH pages AT THE SAME TIME ... how to i prevent this? i have tried if, else and else if, same result every time.
Both of your buttons are enabled, you are checking to see if the buttons are enabled or disabled (clickable or not), not which one has been clicked.
also:if (button2.Enabled == true)
is nested in the first conditional, I'm not sure if that's what you want.
You can: disable buttons 1 and 2 after their clicked so that, for instance button2.Enabled will now = false; (but then you will not be able to reclick that button)
More sophisticated, but better, is to use a delegate for the button3, and assign them in your button1_Click and button2_Click events. Something like this:
private void button1_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.ai_yori_aoshi_5370;
button3.Click += new EventHandler(this.Button3_Click_First);
}
private void button2_Click(object sender, EventArgs e)
{
button3.BackgroundImage = slideshow_test.Properties.Resources.AiYoriAoshi_feature;
button3.Click += new EventHandler(this.Button3_Click_Second);
}
void Button3_Click_First(Object sender,
EventArgs e)
{
// When the button is clicked,
// change the button text, and disable it.
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-guide");
}
void Button3_Click_Second(Object sender,
EventArgs e)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start("http://www.watchcartoononline.com/anime/ai-yori-aoshi-enishi-guide");
}
You may also have to check and make sure an event handler was not previously assigned, in calse someone clicks button1, then button2, then button1 ect. This is described here: Removing event handlers
You can handle your problem by storing the URL of the webpage in a private field, setting it when buttons 1 or 2 are clicked and reading from it after clicking button 3.
private string _address = null;
private void button1_Click(object sender, EventArgs e)
{
// do other stuff
_address = "http://www.watchcartoononline.com/anime/ai-yori-aoshi-guide";
}
private void button2_Click(object sender, EventArgs e)
{
// do other stuff
_address = "http://www.watchcartoononline.com/anime/ai-yori-aoshi-enishi-guide";
}
private void button3_Click(object sender, EventArgs e)
{
if (_address != null)
{
audio.Stop();
if (button1.Enabled || button2.Enabled)
{
timer1.Stop();
pictureBox1.Visible = false;
System.Diagnostics.Process.Start(_address);
}
}
}
I wasn't sure if all the code in button3_Click is necessary, so I cleared it up a little. I might be a bit off, though.
button.Enabled is always true for all buttons by default unless you set it to false. So you cannot use button1.Enabled property to check which button is pressed. try below approach.
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Button1Clicked"] = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
ViewState["Button1Clicked"] = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
if ((bool)ViewState["Button1Clicked"])
{
//open webpage2 code comes here
}
else
{
//open webpage2 code comes here
}
}
I would like to show a product balance in a TextBox when a product is selected from DataGridView.
When product is selected and the tab button is pressed then the product balance should be shown in the TextBox.
All the data is loaded from an Microsoft Access database. How can i achieve this.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
e.Control.KeyPress -= new KeyPressEventHandler(dataGridView1_KeyPress);
if (dataGridView1.CurrentCell.ColumnIndex == 1) //Desired Column
{
//getSum() function gives sum of a db table column
textBox1.Text = getSum();
}
}
I would add a KeyDown and a KeyUp event Handler to the DataGridView Or your Form or whatever can has focus on the time ;).
When the Key, which is pressed down is Tab i would set a member variable to true or false.
Here a short example of what i mean.
public partial class Form1 : Form
{
bool isTabPressed = false;
public Form1()
{
InitializeComponent();
button1.KeyDown += button1_KeyDown;
button1.KeyUp += button1_KeyUp;
}
void button1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
isTabPressed = true;
}
}
void button1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Tab)
{
isTabPressed = false;
}
}
}
Everything else you can do in your method, that you are currently writing and just check if isTabPressed is true.
Hope this helps.
If not leave a comment ;)
EDIT:
So something like this ?
Currently what it does is: you choose something and when you press tab it writes it to the textbox:
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
editControlWasOpened = true;
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1 != null && dataGridView1.CurrentCell != null && dataGridView1.CurrentCell.Value != null && editControlWasOpened )
{
textBox1.Text = dataGridView1.CurrentCell.Value.ToString();
}
valueischanged = false;
}
From what i understand, based on the value you select in you ComboBox, getSum() wiill go and retrieve the total value from the database. If that's the case then add a SelectedIndexChanged event but casting the DataGridViewComboBoxCell into a ComboBox like the code below.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
var combobox = e.Control as ComboBox;
if (combobox != null)
{
combobox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged;
combobox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
}
}
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
var combobox = sender as ComboBox;
if (combobox != null)
{
var item = combobox.SelectedItem.ToString();
if (!string.IsNullOrEmtpy(item))
{
textBox1.Text = getSum();
// Adjust the line above as per your requirement.
// I don't fully understand what getSum() does as you haven't posted it
}
}
}
After a long time this was done .......and i am posting this for other user too!
My Question was
"**I would like to show a product balance in a TextBox when a product is selected from DataGridView. When product is selected and the tab button is pressed then the product balance should be shown in the TextBox. All the data is loaded from an Microsoft Access database. How can i achieve this."
I think the subject is "how to show textbox value when datagridview combobox value is selected"
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0) //Desired Column
{
myCon.Open();
OleDbCommand cmd1 = new OleDbCommand("SELECT sum_stock_purchase_quantity, sum_stock_purchase_quantity_thaan from productPurchaseQuery where stock_product_id=" + this.dataGridView1.CurrentCell.Value.ToString() + "");
cmd1.Connection = myCon;
OleDbDataReader reader = null;
reader = cmd1.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
textBox9.Text = Convert.ToString(reader["sum_stock_purchase_quantity"]);
textBox2.Text = Convert.ToString(reader["sum_stock_purchase_quantity_thaan"]);
}
}
else
{
textBox9.Text = "0.0";
textBox2.Text = "0.0";
}
myCon.Close();
Guys i did this. But this may be good or bad. But my objective is achieved.
I have the following code which checks each radio button (Temp30, Temp40 and Temp60) and does the necessary things such as turning the wash temperature light on etc...
I want to create an event which handles all 3 radio buttons. I thought it could possibly have something to do with the groupbox they are in? (it is called TempGroupBox)
Any help would be much appreciated!
private void Temp30_CheckedChanged(object sender, EventArgs e)
{
if (Temp30.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._30degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp40_CheckedChanged(object sender, EventArgs e)
{
if (Temp40.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._40degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp60_CheckedChanged(object sender, EventArgs e)
{
if (Temp60.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._60degrees;
SpeedGroupBox.Enabled = true;
}
}
You can bind all radioButton's event to the same handler and use sender parameter to get the control that the action is for.
private void Temps_CheckedChanged(object sender, EventArgs e)
{
string checkedName = ((RadioButton)sender).Name;
if(checkedName == "Temp40")
{
...
}
else if(checkedName == "Temp60")
{
...
}
}
You can add event handler for all RadioBUttons's like that after InitializeComponent():
var radioButtons =this.Controls.OfType<RadioButton>();
foreach (RadioButton item in radioButtons)
{
item.CheckedChanged += Temps_CheckedChanged;
}
I'm currently creating a calculator type form on C#. I have four radiobuttons (Addition, subtraction, multi, and div) and a label in between two textboxes. The label changes according to the selected radiobutton, (for example if I selected the Addition radiobutton the label would read "+"). The problem I'm experiencing with this code:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
label3.Text = ("+");
}
else if (radioButton2.Checked == true)
{
label3.Text = ("-");
}
else if (radioButton3.Checked == true)
{
label3.Text = ("x");
}
else if (radioButton4.Checked == true)
{
label3.Text = ("/");
}
}
is when I select the division button the label does not change unless I go through all the buttons and THEN other radio buttons (such as subtraction), when selected, do not change the label until multiple tries. I tried changing the last line to an "else label3.text=("/");" but it doesn't really change anything other than the order of errors.
Any help would be appreciated! Thanks :)
I think you need to check if the radio button is checked in each individual radioButtonX_CheckedChanged method like so:
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
label3.Text = ("+");
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton2.Checked)
{
label3.Text = ("-");
}
}
private void radioButton3_CheckedChanged(object sender, EventArgs e)
{
if (radioButton3.Checked)
{
label3.Text = ("x");
}
}
private void radioButton4_CheckedChanged(object sender, EventArgs e)
{
if (radioButton4.Checked)
{
label3.Text = ("/");
}
}
Let me know if that helps, and if you are still having the issue.
You may want to change how you check for the Checked button. MrB's solution works, but if you'd like to keep your selection code in a single block (as you have), make sure all your radio buttons have their CheckedChanged event subscribed to something similar to the following:
private void RadioButtonCheckedChanged(object sender, EventArgs e)
{
var radioButton = (RadioButton)sender;
if (radioButton.Checked)
{
switch (radioButton.Text)
{
case "Add":
label3.Text = "+";
break;
case "Subtract":
label3.Text = "-";
break;
case "Divison":
label3.Text = "/";
break;
}
}
}
You can also switch on another property, such as the RadioButton.Tag field, whatever may be meaningful to you.
As far as the actual reason your code is failing, it's hard to understand without ensuring which RadioButton's have their events set properly, and seeing the incorrect results.
protected void Page_Load(object sender, EventArgs e)
{
agm.Visible = RadioButtonList1.SelectedValue == "1" ? true : false;
}