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.
Related
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 am working on an interface in C#, which reads data from the serial port and displays it on a graph. I wrote the following code, but the graph doesn't display anything. What is wrong? I don't know exactly what should I modify.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public long rt = 0;
string dataReceived = string.Empty;
private delegate void SetTextDeleg(string text);
// public string kp, kd, ki;
public int distanta;
public string potentiometru;
public Form1()
{
InitializeComponent();
this.chart1.ChartAreas[0].AxisX.Minimum = 0;
this.chart1.ChartAreas[0].AxisY.Minimum = 0;
this.chart1.ChartAreas[0].AxisY.Maximum = 55;
}
private void Connect_button_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
Connect_button.Enabled = false;
}
serialPort1.BaudRate = 9600;// Convert.ToUInt16(comboBox1.Text);
serialPort1.PortName = comboBox3.Text;
serialPort1.DataBits = 8;
serialPort1.StopBits = (System.IO.Ports.StopBits)2;
timer1.Start();
serialPort1.Open();
}
private void Sent_Button_Click(object sender, EventArgs e)
{
// kp = Convert.ToString(Kp_textbox.Text);
//kd = Convert.ToString(Kd_textbox.Text);
//ki = Convert.ToString(Ki_textbox.Text);
//serialPort1.Write(kp);
//serialPort1.Write(ki);
//serialPort1.Write(kd);
//string transmit = "$kp$" + kp + "$kd$" + kd + "$ki$" + ki;
// $kp$0.25
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
string x = serialPort1.ReadLine();
this.BeginInvoke(new SetTextDeleg(DataReceived), new object[] { x });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DataReceived(string data)
{
dataReceived = data.Trim();
if (rt < 2)
return;
if (dataReceived.Contains("."))
{
senzor_textbox.Text = dataReceived;
this.chart1.Series["Distance"].Points.AddXY(0, dataReceived);
}
else
{
potentiometru_textbox.Text = dataReceived;
this.chart1.Series["SetPoint"].Points.AddXY(0, dataReceived);
}
rt = 0;
}
private void button1_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
rt++;
}
private void button2_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen)
serialPort1.Close();
}
}
}
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 :)
Please find the following line in default.aspx.cs
ASPxGridView grid = gvPatient.FindDetailRowTemplateControl(index, "gvOrder") as ASPxGridView;
Its not getting the gvOrder Aspxgridview inside detail row template of gvPatient.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ADLPRO2MODEL;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void gvOrder_BeforePerformDataSelect(object sender, EventArgs e)
{
Session["PatientNo"] = (sender as ASPxGridView).GetMasterRowKeyValue();
}
protected void btnSave_Click(object sender, EventArgs e)
{
// string key = (string)gvPatient.GetMasterRowKeyValue();
decimal key = (decimal)Session["PatientNo"];
int index = gvPatient.FindVisibleIndexByKeyValue(key);
ASPxGridView grid = gvPatient.FindDetailRowTemplateControl(index, "gvOrder") as ASPxGridView;
ASPxMemo tbNote = gvPatient.FindControl("tbNote") as ASPxMemo;
ASPxLabel lblMsg = gvPatient.FindControl("lblMsg") as ASPxLabel;
int patientNo = Convert.ToInt32(grid.GetSelectedFieldValues("PAT_NUMBER")[index]);
int orderKey = Convert.ToInt32(grid.GetSelectedFieldValues("ORDER_KEY")[index]);
ADLPRO2ENTITIES context = new ADLPRO2ENTITIES();
ORD_D_PHA_RECOMMEND obj = context.ORD_D_PHA_RECOMMEND.FirstOrDefault(i => i.ORDER_KEY == orderKey && i.PAT_NUMBER == patientNo);
bool? b = null;
if (obj != null)
{
obj.Cont = b;
if (tbNote.Text.Trim() != string.Empty)
{
obj.Note = tbNote.Text.Trim();
}
}
else
{
obj = new ORD_D_PHA_RECOMMEND();
obj.Cont = b;
if (tbNote.Text.Trim() != string.Empty)
{
obj.Note = tbNote.Text.Trim();
}
obj.ORDER_KEY = orderKey;
obj.PAT_NUMBER = patientNo;
context.AddToORD_D_PHA_RECOMMEND(obj);
}
context.SaveChanges();
tbNote.Text = string.Empty;
lblMsg.Text = "Saved";
}
}
My problem is I can not see any thing on form when I run application. This my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GMap;
using GMap.NET;
using GMap.NET.WindowsForms;
namespace Gmap_tesx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e1)
{
try
{
System.Net.IPHostEntry e =
System.Net.Dns.GetHostEntry("www.google.com");
}
catch
{
gMapControl1.Manager.Mode = AccessMode.CacheOnly;
MessageBox.Show("No internet connection avaible, going to CacheOnly mode.",
"GMap.NET - Demo.WindowsForms", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
}
// config map
GMaps.Instance.Mode = AccessMode.ServerAndCache;
// gMapControl1.CacheLocation = Application.StartupPath + "data.gmdp";
GMaps g = new GMaps();
gMapControl1.MapType = MapType.GoogleSatellite;
gMapControl1.MaxZoom = 6;
gMapControl1.MinZoom = 1;
gMapControl1.Zoom = gMapControl1.MinZoom + 1;
gMapControl1.Position = new PointLatLng(54.6961334816182,
25.2985095977783);
// map events
gMapControl1.OnCurrentPositionChanged += new
CurrentPositionChanged(gMapControl1_OnCurrentPositionChanged);
gMapControl1.OnTileLoadStart += new TileLoadStart(gMapControl1_OnTileLoadStart);
gMapControl1.OnTileLoadComplete += new
TileLoadComplete(gMapControl1_OnTileLoadComplete);
gMapControl1.OnMarkerClick += new MarkerClick(gMapControl1_OnMarkerClick);
gMapControl1.OnMapZoomChanged += new MapZoomChanged(gMapControl1_OnMapZoomChanged);
gMapControl1.OnMapTypeChanged += new MapTypeChanged(gMapControl1_OnMapTypeChanged);
gMapControl1.MouseMove += new MouseEventHandler(gMapControl1_MouseMove);
gMapControl1.MouseDown += new MouseEventHandler(gMapControl1_MouseDown);
gMapControl1.MouseUp += new MouseEventHandler(gMapControl1_MouseUp);
gMapControl1.OnMarkerEnter += new MarkerEnter(gMapControl1_OnMarkerEnter);
gMapControl1.OnMarkerLeave += new MarkerLeave(gMapControl1_OnMarkerLeave);
}
private void gMapControl1_OnCurrentPositionChanged(PointLatLng point)
{
}
private void gMapControl1_OnMarkerLeave(GMapMarker item)
{
}
private void gMapControl1_OnMarkerEnter(GMapMarker item)
{
}
private void gMapControl1_MouseUp(object sender, MouseEventArgs e)
{
}
private void gMapControl1_MouseDown(object sender, MouseEventArgs e)
{
}
private void gMapControl1_MouseMove(object sender, MouseEventArgs e)
{
}
private void gMapControl1_OnMapTypeChanged(MapType type)
{
}
private void gMapControl1_OnMapZoomChanged()
{
}
private void gMapControl1_OnMarkerClick(GMapMarker item, MouseEventArgs e)
{
}
private void gMapControl1_OnTileLoadComplete(long ElapsedMilliseconds)
{
}
private void gMapControl1_OnTileLoadStart()
{
}
}
}