Adding multiple textbox automatically without button in C# - c#

I have created a table and added textbox in it.
I had Use auto post back property with formula to add column 1(ratetexbox) + column 2(QTYtexbox) = column 3,now how to add the total of column 3 in a total.textbox
will adding column 1 + column 2 in column 3 I described a public void addition() and wrote the formula then in textbox of column 1 and 2 i call it.
Hence i got the result(addition) in column 3 textbox.
now i need to calculate all the 7 textbox in column 3 and add it in total.textbox without using button
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Multiply1()
{
int ma1, mb1;
bool isAVaild = int.TryParse(Rate1.Text, out ma1);
bool isBVaild = int.TryParse(Qty1.Text , out mb1);
if (isAVaild && isBVaild )
Amount1.Text = (ma1 * mb1 ).ToString();
else
Amount1.Text = "";
}
protected void Rate1_TextChanged(object sender, EventArgs e)
{
Multiply1();
}
protected void Qty1_TextChanged(object sender, EventArgs e)
{
Multiply1();
}
public void Multiply2()
{
int ma2, mb2;
bool isAVaild = int.TryParse(Rate2.Text, out ma2);
bool isBVaild = int.TryParse(Qty2.Text, out mb2);
if (isAVaild && isBVaild)
Amount2.Text = (ma2 * mb2).ToString();
else
Amount2.Text = "";
}
protected void Rate2_TextChanged(object sender, EventArgs e)
{
Multiply2();
}
public void TotalAmount()
{
int t1,t2 ;
bool isAVaild = int.TryParse(Amount1.Text , out t1);
bool isBVaild = int.TryParse(Amount2.Text , out t2);
//bool isCVaild = int.TryParse(Amount3.Text, out t3);
//bool isDVaild = int.TryParse(Amount4.Text, out t4);
//bool isEVaild = int.TryParse(Amount5.Text, out t5);
//bool isFVaild = int.TryParse(Amount6.Text, out t6);
//bool isGVaild = int.TryParse(Amount7.Text, out t7);
if (isAVaild && isBVaild )
//&& isCVaild && isDVaild && isFVaild && isGVaild )
Totalamount.Text = (t1 + t2 ).ToString();
else
Totalamount.Text = "";
}
protected void Amount1_TextChanged(object sender, EventArgs e)
{
TotalAmount();
}
protected void Amount2_TextChanged(object sender, EventArgs e)
{
TotalAmount();
}
I expected to see the output but it is not showing anything
please help me anyone

Related

Need help integrating the math class in a windows forms calculator

First of all I'm sorry for the bad title. I'm a beginner so I don't have the vocabulary to accurately express what I need help with within one sentence.
I am currently trying to program a calculator. The calculator looks like this:
All of the buttons in the left area are working perfectly, but I'm having trouble coding for the buttons on the right. The program works by simply taking the string in the display and calculating it, but that doesn't work with the buttons on the right. For example I want the display to show √x and calculate the answer by using Math.Sqrt(x) when the user presses the √-button, I don't want the display to show Math.Sqrt(x).
My code looks like this:
public partial class Calculator : Form
{
String mathOperator;
public Calculator()
{
InitializeComponent();
}
private void number_Click(object sender, EventArgs e)
{
if (tbxDisplay.Text == "0")
{
tbxDisplay.Clear();
}
Button btnNumber = (Button)sender;
tbxDisplay.Text = tbxDisplay.Text + btnNumber.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
tbxDisplay.Text = "0";
}
private void operator_Click(object sender, EventArgs e)
{
Button btnOperator = (Button)sender;
mathOperator = btnOperator.Text;
if ((btnOperator.Text == "(" ) && tbxDisplay.Text == "0")
{
tbxDisplay.Clear();
tbxDisplay.Text = tbxDisplay.Text + btnOperator.Text;
}
else
{
tbxDisplay.Text = tbxDisplay.Text + btnOperator.Text;
}
}
private void btnCalculate_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
var v = dt.Compute(tbxDisplay.Text, "");
string answer = v.ToString();
answer = answer.Replace(',', '.');
if (answer.Contains(".0"))
{
answer = answer.TrimEnd('0');
if (answer.EndsWith("."))
answer = answer.TrimEnd('.');
}
tbxDisplay.Text = answer;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (tbxDisplay.Text.Length > 0 && tbxSDisplay.Text.Length != 1)
{
tbxDisplay.Text =
tbxDisplay.Text.Remove(tbxDisplay.Text.Length - 1, 1);
}
if (tbxDisplay.Text.Length == 1)
{
tbxDisplay.Text = "0";
}
}
private void btnBack_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
private void btnPi_Click(object sender, EventArgs e)
{
tbxDisplay.Text = tbxDisplay.Text + "3.14159265359";
//this is my solution for now
//but as you can see it's very ugly
}
}

How to use check a Button in another Button statement? c#

I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}

Error with delegate instruction C#

I'm new on C# and i have many difulties, but now i'm still trying add an eventhandler to declared control like a variable, but if i use the delegate instruction i cant put this events because when i use the declaration:
private delegate void listView1_MouseUp(object sender, MouseEventArgs e)
Many error appears in a procedure that i caught in this forum, but i will put all procedure to you see.
private void Form1_Load(object sender, EventArgs e)
{
// Set the view to show details.
listView1.View = View.Details;
// Allow the user to edit item text.
listView1.LabelEdit = true;
// Allow the user to rearrange columns.
listView1.AllowColumnReorder = true;
// Select the item and subitems when selection is made.
listView1.FullRowSelect = false;
// Display grid lines.
listView1.GridLines = true;
// Sort the items in the list in ascending order.
listView1.Sorting = SortOrder.Ascending;
//Hide Column Header
listView1.HeaderStyle = ColumnHeaderStyle.None;
// Create three items and three sets of subitems for each item.
ListViewItem[] ItemsView = new ListViewItem[Quant_Items];
while (Item_Number <= (Quant_Items - 1))
{
ItemsView[Item_Number] = new ListViewItem(Item_name + Item_Number);
while (Sub_Item <= (Quant_SubItems - 1))
{
ItemsView[Item_Number].SubItems.Add("SubItem" + Sub_Item);
Sub_Item++;
}
Item_Number++;
}
Sub_Item = 0;
while (Sub_Item <= (Quant_SubItems - 1))
{
listView1.Columns.Add("Coluna" + Sub_Item);
Sub_Item++;
}
//Add the items to the ListView.
listView1.Items.AddRange(ItemsView);
//Autosize ListView
listView1.Bounds = new Rectangle(new Point(10, 10), new Size(Quant_SubItems * 70, Quant_Items * 18));
// Add the ListView to the control collection.
this.Controls.Add(listView1);
listView1.MouseUp += new EventHandler(listView1_MouseUp);
}
//____________________________________________________________________
private delegate void listView1_MouseUp(object sender, MouseEventArgs e)
{
ListViewHitTestInfo i = listView1.HitTest(e.X, e.Y);
SelectedLSI = i.SubItem;
if (SelectedLSI == null)
return;
int border = 0;
switch (listView1.BorderStyle)
{
case BorderStyle.FixedSingle:
border = 1;
break;
case BorderStyle.Fixed3D:
border = 2;
break;
}
int CellWidth = SelectedLSI.Bounds.Width;
int CellHeight = SelectedLSI.Bounds.Height;
int CellLeft = border + listView1.Left + i.SubItem.Bounds.Left;
int CellTop = listView1.Top + i.SubItem.Bounds.Top;
// First Column
if (i.SubItem == i.Item.SubItems[0])
CellWidth = listView1.Columns[0].Width;
TxtEdit.Location = new Point(CellLeft, CellTop);
TxtEdit.Size = new Size(CellWidth, CellHeight);
TxtEdit.Visible = true;
TxtEdit.BringToFront();
TxtEdit.Text = i.SubItem.Text;
TxtEdit.Select();
TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
HideTextEditor();
}
private void HideTextEditor()
{
TxtEdit.Visible = false;
if (SelectedLSI != null)
SelectedLSI.Text = TxtEdit.Text;
SelectedLSI = null;
TxtEdit.Text = "";
}
}
}
Thanks for your help!
Just use this:
private void listView1_MouseUp(object sender, MouseEventArgs e)
{
...
}
The delegate keyword doesn't belong in the method declaration, it's not valid in that context.
When you handle an event, you must supply a handler that matches the delegate type expected by this event. Loosley speaking, you need a method with the same signature expected by the handler.
For MouseUp, you need to supply a MouseEventHandler, see https://msdn.microsoft.com/en-us/library/system.windows.forms.mouseeventhandler(v=vs.110).aspx
You need to change the event subscription to
listView1.MouseUp += new MouseEventHandler(listView1_MouseUp);
Then change the signature of your handler to
private void listView1_MouseUp(object sender, MouseEventArgs e) { /*..*/}

How to create the second player/Computer

I am working to create a two player dice game, where the player can either play with another user or the computer. i am having a hard time figuring out how to create a two player game. I am not sure if i have to create separate classes for each user and then create an object of that class to have two separate players or if i just have to create a variable like
static int player = 1;
and assign it to specific areas and use modulus to figure out which player is up.
Also, under my roll_Btn method you will see that i am trying to get it to switch to the next user when the dice rolls a "1" and clear the specified fields, which it does, but the then program ends on me once i try and roll the dice again. See below for my code. thank you for your help and guidance.
public partial class Game : Form
{
public Game()
{
InitializeComponent();
}
static int player = 1;
private void Game_Load(object sender, EventArgs e)
{
oneNameTxt.Text = diceFrm.player1.ToUpper();
twoNameTxt.Text = diceFrm.player2.ToUpper();
}
private void endBtn_Click(object sender, EventArgs e)
{
diceFrm end = new diceFrm();
end.Show();
this.Hide();
}
private void standBtn_Click(object sender, EventArgs e)
{
oneScoreTxt.Text = totalTxt.Text;
}
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = Convert.ToInt32(turnsTxt.Text);
int t2 = t1 + 1;
turnsTxt.Text = t2.ToString();
Random rand = new Random();
int dice = rand.Next(1, 7);
rollTxt.Text = dice.ToString();
int d1 = Convert.ToInt32(totalTxt.Text);
int d2 = d1 + dice;
totalTxt.Text = d2.ToString();
if(dice == 1)
{
player++;
rollTxt.Text = String.Empty;
turnsTxt.Text = String.Empty;
totalTxt.Text = String.Empty;
}
}
private void oneScoreTxt_TextChanged(object sender, EventArgs e)
{
int score1 = Convert.ToInt32(oneScoreTxt.Text);
int score2 = Convert.ToInt32(twoScoreTxt.Text);
if (score1 >= 100 || score2 >= 100)
{
whatLbl.Text = "Winner";
}
else
{
whatLbl.Text = "Turn";
}
}
As Ogul Ozgul said,
private void rollBtn_Click(object sender, EventArgs e)
{
...
if (dice == 1)
{
...
turnsTxt.Text = String.Empty;
...
}
}
When you roll a 1, your turnsTxt.Text = String.Empty, hence when the next time you roll,
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = Convert.ToInt32(turnsTxt.Text); // program crash
...
}
your program will crash horribly.
Solution: I will recommend you use TryParse instead of Convert throughout your code. It will be much more robust.
Eg.
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = 0;
int.TryParse(turnsTxt.Text, out t1)
int t2 = t1 + 1;
turnsTxt.Text = t2.ToString();
...
//rest of your code
}

how do i fill a column in the table using cycle

subj. I get the ID, and it will fill the table. But in this example, only the last entry is filled.
If you announce in page_load "pro = number" - that is filled correctly.
What to do please tell me.
public string idul;
public int pro;
public string nz;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
pro = 5;
}
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = pro; i > -1; i--)
{
wisp();
}
}
public void wisp()
{
SqlConnection con_tsp = new SqlConnection(WebConfigurationManager.ConnectionStrings["JJ"].ConnectionString);
string tsp1 = "UPDATE TSP SET IDUL=#IDUL WHERE NZ=#NZ";
SqlCommand upd_tsp = new SqlCommand(tsp1, con_tsp);
upd_tsp.Parameters.AddWithValue("#NZ", pro);
upd_tsp.Parameters.AddWithValue("#IDUL", "12");
upd_tsp.Connection.Open();
upd_tsp.ExecuteNonQuery();
upd_tsp.Connection.Close();
pro--;
}
You have set Pro as a global variable, on Button2_Click the value will be set to 0 (int's default value)
and then the button click handler will be called hence u r getting only 0 as the input value

Categories