I am trying to have a click event navigate the webBrowser to a pre-set location + string but I can't seem to get it to work.
My biggest issue is maybe getting the string from one event to the click event?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Ink
{
public partial class inkForm : Form
{
public inkForm()
{
InitializeComponent();
}
string searchlink;
private void searchbutton_Click(object sender, EventArgs e)
{
this.AcceptButton = searchbutton;
int itemrow = -1;
String searchValue = searchtextBox.Text.ToUpper();
if (searchValue != null && searchValue != "")
{
foreach (DataGridViewRow row in inkGridView.Rows)
{
if (row.Cells[1].Value.ToString().Equals(searchValue))
{
itemrow = row.Index;
break;
}
else if (row.Cells[1].Value.ToString().Contains(searchValue) && itemrow == -1)
{
itemrow = row.Index;
}
}
if (itemrow == -1)
{
searchtextBox.BackColor = Color.Red;
}
else
{
searchtextBox.BackColor = Color.White;
inkGridView.Rows[itemrow].Selected = true;
inkGridView.FirstDisplayedScrollingRowIndex = itemrow;
}
}
}
private void inkForm_Load(object sender, EventArgs e)
{
this.hPTableAdapter.Fill(this.inkDataSet.HP);
}
private void updatebutton_Click(object sender, EventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure you want to update the stock level?", "Message", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
this.hPTableAdapter.Update(inkDataSet.HP);
inkGridView.Refresh();
MessageBox.Show("Record Updated.", "Success!");
}
}
private void inkGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
inkGridView.Columns["tonerInkDataGridViewTextBoxColumn"].ReadOnly = true;
}
private void inkGridView_SelectionChanged(object sender, EventArgs e)
{
if (inkGridView.SelectedCells.Count > 0)
{
int selectedrowindex = inkGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = inkGridView.Rows[selectedrowindex];
string searchlink = Convert.ToString(selectedRow.Cells["tonerInkDataGridViewTextBoxColumn"].Value);
}
}
private void orderbutton_Click(object sender, EventArgs e)
{
string link;
string searchlink = "blahblah";
link = "http://store.tindallsb2b.co.uk/storefront/evolution_ProductResults.html?strSearch=" + searchlink;
webBrowser.Url = new Uri(link);
}
private void urlcheckertextbox_TextChanged(object sender, EventArgs e)
{
urlcheckertextbox.Text = webBrowser.Url.ToString();
}
}
}
When button is clicked, it navigates the domain to a "unknown location" page on the website (The website is not owned by me).
The idea is to click the cell in the DataGridView which is a product code, then click the button which adds the product code to the set url and loads the url+string in the webBrowser.
Your vairable searchlink isn't visible to your orderbutton_Click(). A solution would be to declare the varible searchlink outside of the methods in your class. In fact you are using completely different variables (both named searchlink) inside your methods.
So for example:
class testclass
{
string teststring1 = ""; //visible in both methods
private void testmethod1()
{
string teststring2 = ""; //only visible in this method
teststring1 = "it works!";
}
private void testmethod2()
{
teststring2 = "this won't compile"; //teststring2 is not visible here
teststring1 = "it works, too";
//but what you are doing is:
string teststring2 = ""; //new variable (not related to teststring2 from above)
}
}
And as bkribbs told me this is called a variable scope. Thanks!
For solving your specific problem here is the new code:
string searchlink = "";
private void inkGridView_SelectionChanged(object sender, EventArgs e)
{
if (inkGridView.SelectedCells.Count > 0)
{
int selectedrowindex = inkGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = inkGridView.Rows[selectedrowindex];
searchlink = Convert.ToString(selectedRow.Cells["tonerInkDataGridViewTextBoxColumn"].Value);
}
}
private void orderbutton_Click(object sender, EventArgs e)
{
string link;
link = "http://store.tindallsb2b.co.uk/storefront/evolution_ProductResults.html?strSearch=" + searchlink;
webBrowser.Url = new Uri(link);
}
I hope I got your problem right :)
Related
This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I am a newbie in C# and I have questions as below:
I have a Form1 name is setting Port Name, Baud Rate, Parity... of modbus protocol and I can open serial Port.
Also, I have another Form is called Form2, When Port is opened i want to close Form1 and Port alway Open => I can do it. But this problem that was I want to get data such as FC03 HolodingRegister, FC01 WriteSingleCoil... for Form2 but didnot.
I used delegate to transfer data from Form 1 to Form 2 but I could not use button Form2 to send FC01 signal.
How to use FC01, FC03,04... for Form2 when Form 1 connected.
Code Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using Modbus.Device;
namespace ATS
{
public partial class frCommunication : Form
{
SerialPort serialPort = new SerialPort();
ModbusMaster Master;
public delegate void truyendulieu(string text);
public truyendulieu truyendata;
public delegate void truyendulieu1(string text1);
public truyendulieu1 truyendata1;
public delegate void truyendulieu2(string text2);
public truyendulieu2 truyendata2;
public frCommunication()
{
InitializeComponent();
}
private void frCommunication_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cboxPort.Items.AddRange(ports);
cboxPort.SelectedIndex = 0;
}
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
try
{
serialPort.PortName = cboxPort.Text;
serialPort.BaudRate = Convert.ToInt32(cboxBaudRate.Text);
serialPort.DataBits = Convert.ToInt32(cboxDataBits.Text);
serialPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cboxStopBits.Text);
serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboxParity.Text);
serialPort.Open();
Master = ModbusSerialMaster.CreateRtu(serialPort);
Master.Transport.Retries = 0; // don't have to to retries
Master.Transport.ReadTimeout = 300;//miliseconds
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (serialPort.IsOpen)
{
lblDisplay.Text = "Connected";
lblDisplay.ForeColor = System.Drawing.Color.Red;
cboxBaudRate.Enabled = false;
}
else
{
lblDisplay.Text = "Disconnected";
MessageBox.Show("Error!");
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
try
{
serialPort.Close();
lblDisplay.Text = "Disconnected";
lblDisplay.ForeColor = System.Drawing.Color.Green;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
ushort[] holding_register = Master.ReadHoldingRegisters(1, 0, 10);
txtV_Grid.Text = Convert.ToString(holding_register[0]);
txtC_Grid.Text = Convert.ToString(holding_register[1]);
txtP_Grid.Text = Convert.ToString(holding_register[2]);
}
}
private void btnStart_Click(object sender, EventArgs e)
{
if (txtV_Grid.Text.Length > 0 || txtC_Grid.Text.Length > 0 || txtP_Grid.Text.Length > 0)
{
if (truyendata != null || truyendata1 != null)
{
truyendata(txtV_Grid.Text);
truyendata1(txtC_Grid.Text);
truyendata2(txtP_Grid.Text);
}
this.Hide();
}
}
private void txtV_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata != null)
{
truyendata(txtV_Grid.Text);
}
}
private void txtC_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata1 != null)
{
truyendata1(txtC_Grid.Text);
}
}
private void txtP_Grid_TextChanged(object sender, EventArgs e)
{
if (truyendata2 != null)
{
truyendata2(txtP_Grid.Text);
}
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void btnOn_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn On ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, true);
}
else
{
Master.WriteSingleCoil(1, 0, false);
}
}
}
private void btnOff_ACB_Grid_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen)
{
DialogResult dl = MessageBox.Show("Would you like to turn Off ACB_GRID", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dl == DialogResult.Yes)
{
Master.WriteSingleCoil(1, 0, false);
}
else
{
Master.WriteSingleCoil(1, 0, true);
}
}
}
}
}
Code Form2:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SymbolFactoryDotNet;
namespace ATS
{
public partial class frMain : Form
{
public frMain()
{
InitializeComponent();
}
private void communicationToolStripMenuItem_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.ShowDialog();
}
private void standardControl1_Load(object sender, EventArgs e)
{
}
private void LoadData(string data)
{
txtV.Text = "";
txtV.Text = data;
}
private void LoadData1(string data1)
{
txtC.Text = "";
txtC.Text = data1;
}
private void LoadData2(string data2)
{
txtP.Text = "";
txtP.Text = data2;
}
private void btnConnect_Click(object sender, EventArgs e)
{
frCommunication frm = new frCommunication();
frm.truyendata = new frCommunication.truyendulieu(LoadData);
frm.truyendata1 = new frCommunication.truyendulieu1(LoadData1);
frm.truyendata2 = new frCommunication.truyendulieu2(LoadData2);
frm.ShowDialog();
}
private void txtV_TextChanged(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if(picOn.Visible == false)
{
picOn.Visible = true;
picOff_Grid.Visible = false;
// standardControl3.DiscreteValue2 = true;
}
else
{
picOn.Visible = false;
picOff_Grid.Visible = true;
}
}
private void frMain_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss dd-MM-yyyy");
}
private void btnOn_Grid_Click(object sender, EventArgs e)
{
}
}
}
When I understand you right, you will in Form1 open a connection, close the Form, open a new Form2 and use this connection there?
Well, when that's the case, you could make an special Connection Singleton to hold this connection then you can use it in your Form2
using System;
namespace Sandbox
{
public sealed class Connection
{
private static readonly Lazy<Connection> _instance = new Lazy<Connection>(() => new Connection());
public static Connection Instance => _instance.Value;
private Connection()
{ }
// Implement your Connection Code here.
}
}
I'm trying to realize web searches to get the title of websites on a Google search.
I got a code that works well on other sites, but using Google I got duplicated results.
I have tried and tried, but I can't see where is the mistake.
Code simplified:
public partial class Form1 : Form
{
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etiqueta in navegador.Document.All)
{
if (etiqueta.GetAttribute("classname").Contains("LC20lb DKV0Md"))
{
listBox1.Items.Add(etiqueta.InnerText);
}
}
}
catch (Exception exception) { }
}
private void function(object sender, EventArgs e)
{
/// string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate("https://google.com/search?q=water");
/// this.Text = query;
}
}
Result:
I don't know how google works but you can prevent duplicates like this
if(!listBox1.Items.Contains(etiqueta.InnerText))
listBox1.Items.Add(etiqueta.InnerText);
After a couple of days researching and improving the code I decided to change the list for a table.
In addition, now the searches are not duplicated and are positioned in the table as expected
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SourceDownloader
{
public partial class Form1 : Form
{
strs valor = new strs();
public Form1()
{
InitializeComponent();
}
WebBrowser navegador = new WebBrowser();
private void Form1_Load(object sender, EventArgs e)
{
navegador.ScriptErrorsSuppressed = true;
navegador.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.datos);
}
private void datos(object sender, EventArgs e)
{
try
{
foreach (HtmlElement etq in navegador.Document.All)
{
if (etq.GetAttribute("classname").Contains("r")) /// LC20lb DKV0Md
{
foreach (HtmlElement a_et in etq.GetElementsByTagName("a"))
{
valor.link = a_et.GetAttribute("href");
}
foreach (HtmlElement t_et in etq.GetElementsByTagName("h3"))
{
valor.tit = t_et.InnerText;
}
bool exist = dataGridView1.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["link"].Value) == valor.link);
var s1 = valor.link;
bool b = s1.Contains("google.com");
bool a = s1.Contains("googleusercontent");
if (!exist /* && !b && !a*/)
{
dataGridView1.Rows.Insert(0, valor.tit, valor.link);
}
}
if (etq.GetAttribute("classname").Contains("G0iuSb"))
{
valor.next = etq.GetAttribute("href");
}
}
more_ops.Enabled = true;
}
catch (Exception)
{
}
}
private void function(object sender, EventArgs e)
{
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
private void more_ops_Click(object sender, EventArgs e)
{
string query = valor.next;
navegador.Navigate(query);
this.Text = query;
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
try
{
var msg = dataGridView1.CurrentCell.Value;
System.Diagnostics.Process.Start(msg.ToString());
}
catch (Exception)
{
MessageBox.Show("Error");
}
}
private void Enter(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
string texto = query_box.Text;
texto = texto.Replace("\n", "");
query_box.Text = texto;
string query = "https://google.com/search?q=" + query_box.Text;
navegador.Navigate(query);
this.Text = query;
}
}
}
/// global values
class strs
{
private string _link = "N/A";
private string _tit = "N/A";
private string _next = "N/A";
public string tit
{
get
{
return _tit;
}
set
{
_tit = value;
}
}
public string link
{
get
{
return _link;
}
set
{
_link = value;
}
}
public string next
{
get
{
return _next;
}
set
{
_next = value;
}
}
}
}
I have created a windows form application in the namespace TestUI, it has a customer class, instantiated as below:
List<Customer> cl = db.Customers.ToList();
But Customer points to an auto-generated class file in the same namespace TestUI.Customer. I have created a new class DataLayerTest.Customer but I dont know how to make the original reference this class.
I have tried adding a using statement to the top of the file, and whilst I can reference it if I rename it I cant access it in place of the auto-generated class.
Here is the code of my CustomerForm :
using TestDataModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestUI
{
public partial class CustomerForm : Form
{
public CustomerForm()
{
InitializeComponent();
}
private void ClearButton_Click(object sender, EventArgs e)
{
custListBox.ClearSelected();
}
private void AddNewCustButton_Click(object sender, EventArgs e)
{
this.Hide();
CreateCustomer cc = new CreateCustomer();
cc.ShowDialog();
}
private void CustomerForm_Load(object sender, EventArgs e)
{
Test2UEntitiesA db = new Test2UEntitiesA();
List<Customer> cl = db.Customers.ToList();
custListBox.DataSource = cl;
custListBox.DisplayMember ="CustomerName";
takeNewOrderButton.Enabled = false;
}
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Customer customer = (Customer)custListBox.SelectedItem;
label1.Text = customer.CustomerNumber.ToString();
label2.Text = customer.CustomerName;
takeNewOrderButton.Enabled = true;
}
private void TakeNewOrderButton_Click_1(object sender, EventArgs e)
{
OrderBasketForm ob = new OrderBasketForm((Customer)custListBox.SelectedItem);
ob.Show();
this.Hide();
}
}
}
And this is the code for the order form which uses the customer object
using TestDataModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace TestUI
{
public partial class OrderBasketForm : Form
{
Customer cust;
public static OrderBasket ob;
public OrderBasketForm(Customer customer)
{
InitializeComponent();
cust = customer;
ob = new OrderBasket();
Test2UEntitiesA db = new Test2UEntitiesA();
List<Product> pl = db.Products.ToList();
label2.Text = cust.CustomerName;
discValue.Text = cust.Discount.ToString();
}
private void CancelButton_Click(object sender, EventArgs e)
{
this.Hide();
CustomerForm cf = new CustomerForm();
cf.ShowDialog();
}
private void AddButton_Click(object sender, EventArgs e)
{
int quantity;
Product product = (Product)productNameBox.SelectedItem;
quantity = (int)quantityCounter.Value;
if (quantity <= 0)
{
MessageBox.Show("No quantity has been selected", "Quantity Invalid", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
return; //No items selected
}
else
{
ob.AddProduct(product.ProductNumber, product.ProductName, product.Price, product.RecommendedRetailPrice, quantity, product.Description);
BasketItemsToListView();
}
}
public void BasketItemsToListView()
{
basketListView.Items.Clear();
numOfItems.Text = ob.NumberOfItems.ToString();
numOfProducts.Text = ob.NumberOfProducts.ToString();
totalBox.Text = string.Format("{0:C2}", ob.BasketTotal);
discTotal.Text = string.Format("{0:C2}", ob.BasketTotal);
//Using ListView Control to display basket contents
foreach (BasketItem bItem in ob.BasketItems)
{
ListViewItem item = new ListViewItem(new[]
{
bItem.ProductNumber.ToString(),
bItem.ProductName,
});
basketListView.Items.Add(item);
}
clearButton.Enabled = true;
}
private void ClearButton_Click(object sender, EventArgs e)
{
DialogResult clearResponse = MessageBox.Show("Are you sure you want to clear the basket?", "Clear Basket", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
if (clearResponse == DialogResult.Yes)
{
ClearBasket();
}
}
private void ClearBasket()
{
ob.ClearBasket();
BasketItemsToListView();
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
private void RemoveButton_Click(object sender, EventArgs e)
{
if (basketListView.SelectedItems.Count <= 0)
return; //No items selected
ob.RemoveProduct(Int32.Parse(basketListView.SelectedItems[0].Text));
BasketItemsToListView();
removeButton.Enabled = false;
}
private void CheckOutButton_Click(object sender, EventArgs e)
{
if (ob.NumberOfItems == 0)
{
MessageBox.Show("The basket is currently empty!", "Basket Empty", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
return;
}
Test2UEntitiesA db = new Test2UEntitiesA();
List<OrderItem> itemsToAdd = new List<OrderItem>();
//create list populate with orderbasket
foreach (BasketItem item in ob.BasketItems)
{
itemsToAdd.Add(new OrderItem
{
ProductNumber = item.ProductNumber,
Quantity = item.Quantity
});
}
//create an order object - needs to match the format of database table
Order order = new Order
{
OrderDate = DateTime.Now,
CustomerNumber = cust.CustomerNumber,
CustomerDiscount = cust.Discount,
OrderStatus = 1,
OrderTotalBeforeDiscount = ob.BasketTotal,
OrderItems = itemsToAdd
};
//save changes to db
db.Orders.Add(order);
db.SaveChanges();
OrderHistoryForm ohf = new OrderHistoryForm(cust);
ohf.Show();
this.Hide();
}
}
}
If in case you have more than one project in your solution, you can manually add the reference to that project by editing the .csproj file and adding this block to it
<ItemGroup>
<ProjectReference Include="..\ProjectName\ProjectName.csproj" />
</ItemGroup>
then the using statement will work. Visula studio sometimes runs into an error trying to do this by itself.
But also, you should first try opening the main .cs file which you are trying to use but can't find it in the other file, change its namespace and then try referencing it again. Sometimes our naming conventions conflict with .Net namespaces or class libraries which you may have never heard of.
So I have this calculator http://gyazo.com/589156935eec141c3aedf83b9f960d29 (not enough reputation sorry)
When I type [1] and then [2] the display shows [12]
If I press a operator for example [+] the number 12 is still supposed to be shown in the display.
But, if I now start typing new numbers The old ones are supposed to be removed from the display. But i can't get this to work.
My form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Miniräknare
{
public partial class Form1 : Form
{
Miniräknare miniräknare;
public Form1()
{
InitializeComponent();
miniräknare = new Miniräknare(0, 0, "", 0, false);
}
private void btnEquals_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.doEquals();
}
private void btnNum1_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("1", tbxWindow.Text);
}
private void btnNum2_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("2", tbxWindow.Text);
}
private void btnNum3_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("3", tbxWindow.Text);
}
private void btnNum4_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("4", tbxWindow.Text);
}
private void btnNum5_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("5", tbxWindow.Text);
}
private void btnNum6_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("6", tbxWindow.Text);
}
private void btnNum7_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("7", tbxWindow.Text);
}
private void btnNum8_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("8", tbxWindow.Text);
}
private void btnNum9_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand("9", tbxWindow.Text);
}
private void btnNum0_Click(object sender, EventArgs e)
{
if (tbxWindow.Text != "") tbxWindow.Text = miniräknare.getOperand("0", tbxWindow.Text);
}
private void btnOperatorDivision_Click(object sender, EventArgs e)
{
}
private void btnOperatorTimes_Click(object sender, EventArgs e)
{
}
private void btnOperatorPlus_Click(object sender, EventArgs e)
{
miniräknare.Op = "+";
}
private void btnOperatorMinus_Click(object sender, EventArgs e)
{
miniräknare.Op = "-";
miniräknare.Change = true;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
tbxWindow.Text = miniräknare.getOperand(",", tbxWindow.Text);
}
private void btnClear_Click(object sender, EventArgs e)
{
}
private void btnSin_Click(object sender, EventArgs e)
{
}
private void btnCos_Click(object sender, EventArgs e)
{
}
private void btnTan_Click(object sender, EventArgs e)
{
}
private void btnSquared_Click(object sender, EventArgs e)
{
}
private void btnModulus_Click(object sender, EventArgs e)
{
}
private void btnExponential_Click(object sender, EventArgs e)
{
}
private void btnlogarithm_Click(object sender, EventArgs e)
{
}
private void btn1OverX_Click(object sender, EventArgs e)
{
}
private void btnLn_Click(object sender, EventArgs e)
{
}
private void btnPi_Click(object sender, EventArgs e)
{
}
private void btnMemoryClear_Click(object sender, EventArgs e)
{
}
private void btnMemoryRecall_Click(object sender, EventArgs e)
{
}
private void btnMemorySave_Click(object sender, EventArgs e)
{
}
}
}
My class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Miniräknare
{
class Miniräknare
{
private double first;
private double second;
private string op;
private double memory;
private bool change;
public Miniräknare(double first, double second, string op, double memory, bool change)
{
this.first = 0;
this.second = 0;
this.op = "";
this.memory = 0;
this.change = false;
}
public double First
{
get {return first; }
set { first = value; }
}
public double Second
{
get { return second; }
set { second = value; }
}
public string Op
{
get { return op; }
set { op = value; }
}
public double Memory
{
get { return memory; }
set { memory = value; }
}
public bool Change
{
get { return change; }
set { change = value; }
}
public string getOperand(string t, string textBox)
{
textBox = textBox + t;
if (t.Equals(","))
{
change = true;
second = double.Parse(textBox);
}
else if (op.Equals(""))
{
if (!change)
{
textBox = "";
change = true;
textBox = textBox + t;
}
first = double.Parse(textBox);
}
else
{
if (!change)
{
textBox = "";
change = true;
textBox = textBox + t;
}
second = double.Parse(textBox);
}
return textBox;
}
/* public string calculateAnswer()
{
} */
public string doEquals()
{
if (op == "-" ) return (first - second).ToString();
else return null;
}
}
}
In the following block after pressing "+" button "change" is true and the block is skipped when type the first digit of the second number.
else
{
if (!change)
{
textBox = "";
change = true;
textBox = textBox + t;
}
second = double.Parse(textBox);
}
since you assigned textBox at the beginning of the getOperand method, it will return the value combining what you already had on the screen with the new char.
public string getOperand(string t, string textBox)
{
textBox = textBox + t;
This should do the trick:
public string getOperand(string t, string textBox)
{
if (t.Equals(","))
{
textBox = textBox + t;
change = true;
second = double.Parse(textBox);
}
else if (Op.Equals(""))
{
textBox = textBox + t;
if (!change)
{
textBox = "";
change = true;
textBox = textBox + t;
}
first = double.Parse(textBox);
}
else
{
if (!change)
{
textBox = textBox + t;
}
else
{
textBox = t;
change = false;
}
second = double.Parse(textBox);
}
return textBox;
}
I know this is not https://codereview.stackexchange.com/ and this does not answer the question asked (which has already been answered) and might be marked as off-topic, but wanted to show the changes as suggested in the various comments in an orderly fashion, just to help you improve your coding (current and future) experience.
Changes that can be made to your Miniräknare class (Comments added to explain):
public class Miniräknare
{
public Miniräknare()
{
// Have a default constructor that sets all the default properties
First = 0;
Second = 0;
Op = "";
Memory = 0;
Change = false;
}
public Miniräknare(double first, double second, string op, double memory, bool change)
{
// If you have a constructor with parameters, use the parameters to set your properties
First = first;
Second = second;
Op = op;
Memory = memory;
Change = change;
}
// Use automatic properties, this improves readability and less confusion (As per D Stanley in comments)
public double First { get; set; }
public double Second { get; set; }
public string Op { get; set; }
public double Memory { get; set; }
public bool Change { get; set; }
public string getOperand(string t, string textBox)
{
// Apply changes as per the accepted answer
textBox = textBox + t;
if (t.Equals(","))
{
Change = true;
Second = double.Parse(textBox);
}
else if (Op.Equals(""))
{
if (!Change)
{
textBox = "";
Change = true;
textBox = textBox + t;
}
First = double.Parse(textBox);
}
else
{
if (!Change)
{
textBox = "";
Change = true;
textBox = textBox + t;
}
Second = double.Parse(textBox);
}
return textBox;
}
public string doEquals()
{
if (Op == "-") return (First - Second).ToString();
else return null;
}
}
Changes in your Form1:
Instantiate your miniräknare variable now like this, since you where setting them to the defaults with your original input parameters.
miniräknare = new Miniräknare();
Replace all your btnNum1_Click to btnNum9_Click event handlers with this single event handler to improve readability and volume of your code (Check additional comments in the code):
private void btnNumber_Click(object sender, EventArgs e)
{
// !! Remember !! to set the Tag value of each of your buttons to their corresponding values
// Then change btnNum1 to btnNum9's Click events to btnNumber_Click
// Additionally you can also just use ((Button)sender).Text if their text values will never change
// You could even do this with your operators, unless you have specific code for the button (like you have for btnNum0)
tbxWindow.Text = miniräknare.getOperand(((Button)sender).Tag as String, tbxWindow.Text);
}
I've got the following code: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace Testing.Event_Delegate
{
public partial class WebForm1 : System.Web.UI.Page
{
WebUserControl2 QT2;
WebUserControl3 QT3;
DataTable dtQuestionSet;
protected void Page_Init(object sender, EventArgs e)
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
Session["Counter"] = 0;
Session["QuestionCount"] = 0;
Session["CompletedInsp"] = false;
}
//check to see if the inspection process is complete and display pass\fail and log. Else carry on.
if (Convert.ToBoolean(Session["CompletedInsp"]) == true)
{
//Response.Write("Failed");
ModalPopupExtender2.Show();
return;
}
// all controls need to be rendered every page postback otherwise the rest of the code loses scope.
QT2 = (WebUserControl2)this.LoadControl("WebUserControl2.ascx");
UC2BtnClickEvent.MyEvent2 += new UC2BtnClickEvent.OnMyEvent2(ChecKResult);
QT3 = (WebUserControl3)this.LoadControl("WebUserControl3.ascx");
UC2BtnClickEvent.MyEvent3 += new UC2BtnClickEvent.OnMyEvent3(ChecKResult);
PlaceHolder2.Controls.Add(QT2);
PlaceHolder2.Controls.Add(QT3);
QT2.Visible = false;
QT3.Visible = false;
if (IsPostBack == false)
{
dtQuestionSet = new DataTable();
MakeDataTabledtQuestionSet();
}
else
{
dtQuestionSet = (DataTable)Session["DataTableW"];
}
Session["DataTableW"] = dtQuestionSet;
}
void ChecKResult(object sender, EventArgs e, string strTextBox, string strMyDescription)
{
Label1.Text = "You Answered: - " + strMyDescription;
if (Convert.ToInt32(Session["Counter"]) > Convert.ToInt32(Session["QuestionCount"]))
{
Session["CompletedInsp"] = true;
}
else
{
//carry on with inspection
Session["Counter"] = Convert.ToInt32(Session["Counter"]) + 1;
dtQuestionSet = (DataTable)Session["DataTableW"];
RunInspection();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("WebForm1.aspx");
}
protected void cmdStartInspection_Click(object sender, EventArgs e)
{
Session["Counter"] = 0;
GetQuestions();
}
protected void GetQuestions()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["PromptedInspConnectionString"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("test.GetQuestions", conn);
SqlDataReader dr = null;
cmd.CommandType = CommandType.StoredProcedure;
//cmd.Parameters.Add(new SqlParameter("#Block1", cmbBlock1.Text));
dr = cmd.ExecuteReader();
while (dr.Read())
{
DataRow drQuestions = dtQuestionSet.NewRow();
drQuestions["QuestionText"] = dr[1].ToString();
drQuestions["ExpectedResponse"] = dr[2].ToString();
drQuestions["QuestionType"] = dr[3].ToString();
dtQuestionSet.Rows.Add(drQuestions);
}
Session["DataTableW"] = dtQuestionSet;
Session["QuestionCount"] = dtQuestionSet.Rows.Count;
conn.Close();
RunInspection();
}
protected void RunInspection()
{
switch (dtQuestionSet.Rows[Convert.ToInt32(Session["counter"])][2].ToString())
{
case "1":
QT2.QuestionText = dtQuestionSet.Rows[0][0].ToString();//"I'm asking a question 1";
QT2.Visible = true;
break;
case "2":
QT3.QuestionText = dtQuestionSet.Rows[0][0].ToString();//"I'm asking a question 2";
QT3.Visible = true;
break;
}
}
private void MakeDataTabledtQuestionSet()
{
dtQuestionSet.Columns.Add("QuestionText");
dtQuestionSet.Columns.Add("ExpectedResponse");
dtQuestionSet.Columns.Add("QuestionType");
}
}
}
When I click on the button on a usercontrol with the code: -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Testing.Event_Delegate
{
public partial class WebUserControl2 : System.Web.UI.UserControl
{
string questionAsked;
public string QuestionText
{
set { questionAsked = value; }
get { return questionAsked; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = QuestionText;
TextBox1.Focus();
}
protected void Button1_Click(object sender, EventArgs e)
{
UC2BtnClickEvent bEvent = new UC2BtnClickEvent();
bEvent.onRefresh2Event3(sender, e, TextBox1.Text, TextBox1.Text );
TextBox1.Text = "";
}
}
}
It runs the procedure CheckResults 3 times on the aspx page when I only need it to run once.
UC2BtnClickEvent.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Testing.Event_Delegate
{
public class UC2BtnClickEvent
{
public delegate void OnMyEvent2(object sender, EventArgs e, string strTextBox, string strMyDescription);
public static event OnMyEvent2 MyEvent2;
public virtual void onRefresh2Event2(object sender, EventArgs e, string strTextBox, string strMyDescription)
{
if (MyEvent2 != null)
{
MyEvent2(sender, e, strTextBox, strMyDescription);
}
}
public delegate void OnMyEvent3(object sender, EventArgs e, string strTextBox, string strMyDescription);
public static event OnMyEvent3 MyEvent3;
public virtual void onRefresh2Event3(object sender, EventArgs e, string strTextBox, string strMyDescription)
{
if (MyEvent3 != null)
{
MyEvent3(sender, e, strTextBox, strMyDescription);
}
}
}
}
What have I done wrong to make this happen please as it should only run once.