Replace characters in string with another character and switch back - c#

Quick note - I am very new to c# so I apologize if this is stupid simple.
I am having a hard time trying to complete a simple c# task in a book.
Pseudocode-
Text box text = user input
if button one is clicked
replace all capital letters in the text box with an asterisk
else if button two is clicked
replace the asterisks with their original characters (back to normal)
Here is what I have so far
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.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new System.EventHandler(ClickedButton);
button2.Click += new System.EventHandler(ClickedButton);
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void ClickedButton(object sender, EventArgs e)
{
string orignalText = textBox1.Text;
if (sender == button1)
{
string replaced = Regex.Replace(orignalText, #"[A-Z]", "*");
textBox1.Text = (replaced);
}
else if (sender == button2)
{
textBox1.Text = (orignalText);
}
}
}
}
The problem is that button2 is showing the text with the asterisks. It should be showing (I want it to show) the original characters.

The originalText should be a class field instead of a local variable. Also you should not store a textbox's value in case if someone clicked on the button2. Try to replace your ClickedButton method with this:
string orignalText;
public void ClickedButton(object sender, EventArgs e)
{
if (sender == button1)
{
orignalText = textBox1.Text;
string replaced = Regex.Replace(orignalText, #"[A-Z]", "*");
textBox1.Text = replaced;
}
else if (sender == button2)
{
textBox1.Text = orignalText;
}
}

You have 2 issues. First, you're setting the originalText before knowing which button was pressed. Second, originalText is a local variable, so when you want to replace it back in, it won't contain the original text anymore.

You just need to globalize originaltext variable and move the line
string orignalText = textBox1.Text;
into the first if check.

try this:
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.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new System.EventHandler(ClickedButton);
button2.Click += new System.EventHandler(ClickedButton);
}
private void Form1_Load(object sender, EventArgs e)
{
}
string orignalText = null; //you should define this var outside of ClickedButton method to keep its value during button1/2 clicks
public void ClickedButton(object sender, EventArgs e)
{
if (sender == button1)
{
orignalText = textBox1.Text;
string replaced = Regex.Replace(orignalText, #"[A-Z]", "*");
textBox1.Text = replaced;
}
else if (sender == button2)
{
if (orignalText != null) textBox1.Text = orignalText;
}
}
}
}

Related

why can't I add a new List object in button event

why can't I add a new item/object to my list in button (or combobox etc.) events? I mean, the events don't see my list if it's outside of the brackets...it's underlined in red... can you help me?
long story short: i want to add a new object by clicking the button
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.Xml.Serialization;
using System.IO;
namespace Samochody
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Samochod> ListaSamochodow = new List<Samochod>();
comboBox1.DataSource = ListaSamochodow;
comboBox1.DisplayMember = "Marka";
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ListaSamochodow.Add(new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text)));
}
catch (Exception oException)
{
Console.WriteLine("Aplikacja wygenerowała następujący wyjątek: " + oException.Message);
}
}
I think you should instantiate your list globally and not under Form1_Load event.
that way it will be accessible all around your class (the window in this case).
This seems to work fine. You might need to set your textboxes to contain valid values when you start the form. also make sure that you make the list visible throughout your form1 class.
namespace Samochody
{
public partial class Form1 : Form
{
// make sure your list looks like this, created outside your functions.
List<Samochod> ListaSamochodow = new List<Samochod>();
public Form1()
{
InitializeComponent();
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
textBox1.Text = "string here";
textBox2.Text = "string here";
textBox3.Text = "100";
}
private void Form1_Load(object sender, EventArgs e)
{
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click_1(object sender, EventArgs e)
{
Samochod s = new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
ListaSamochodow.Add(s);
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
}
}
}

How to make a customized progressbar in c#

I would like to learn how to make a progressbar like the one shown in this video.
I tried to replicate it in VS C#, but I get the error:
C# Property or indexer cannot be assigned to -- it is read only
If I try using if (txProgressBar.Text.Length == 85), I will get this in the TextBox (txProgressBar)
System.Windows.Forms.TextBox, Text: System.Windows.Forms.TextBox, Text: Syst...██
Textbox Progressbar Tutorial VB 2010
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 CustomizedProgressBar
{
public partial class Form1 : Form
{
int last = 1;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (txProgressBar.Text.Length = "85")
{
timer1.Stop();
MessageBox.Show("Counted!");
}else
{
if (last == 1)
{
txProgressBar.Text = txProgressBar + "█";
last = 2;
}
else
{
txProgressBar.Text = txProgressBar.Text + "█";
last = 1;
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txProgressBar.Text = "";
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
Your line:
txProgressBar.Text = txProgressBar + "█";
should be
txProgressBar.Text = txProgressBar.Text + "█"; or txProgressBar.Text &= "█";
I realized what was the problem. The txProgressBar.Text = txProgressBar + "█"; was missing the *.Text. That solved the problem and the message is shown as well.

Form submit issue when invoking click?

I'm trying to make a small program that loads a webpage into the form submits the form on the
page automaticlly - this is apart of a larger project but i cant get this part work properly.
This web page offer Court cases results when the correct case number and date (mm-yy) is typed in and submitted.
I created a simple webBrowser in a form and called it webBrowser1.
And here is my Form.cs Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
firstStep();
// secondStep();
}
private void firstStep()
{
webBrowser1.Url = new System.Uri("http://www.court.gov.il/NGCS.Web.Site/HomePage.aspx", System.UriKind.Absolute);
}
private void HandleRequest(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(HandleRequest);
HtmlElement caseNumber = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaCaseNumberTextBoxHT"];
HtmlElement caseDate = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaMonthYearTextBoxHT"];
caseNumber.Focus();
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(2)");
System.Windows.Forms.SendKeys.Send("(2)");
System.Windows.Forms.SendKeys.Send("(3)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("{TAB}");
System.Windows.Forms.SendKeys.Send("(0)");
System.Windows.Forms.SendKeys.Send("(3)");
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(0)");
HtmlElement inputTag = webBrowser1.Document.All["Header1_CaseLocatorHeaderUC2_SearchHeaderCaseButton"];
inputTag.InvokeMember("Click");
}
}
}
As you can see - I'm typing the values as shown in the picture and then invoking a click on the button that submits this form, but it doesn't work!? this webpage is very tricky and uses scripts that validate the input and then sets the correct values to be submits and by the way he works only on IE < 10....
any idea please?
EDIT:
Its working now - I am firing the invoke twice but I don't have an idea what was the problem.
Now the new problem is that I added a button click that fires the process btnGet_Click and when triggering this function I get an error - it seems that DetailsTag is set to null... but when I un-comment the function in the public Form1() its working fine and loading the website as it should.
What is the difference between calling the the function firstStep() in the button click / public form?
why I receive this error?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private readonly object lock_ = new object();
HtmlElement caseNumber;
HtmlElement caseDate;
HtmlElement DetailsTag;
int checks = 1;
public Form1()
{
InitializeComponent();
//webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
//firstStep();
}
private void firstStep()
{
webBrowser1.Url = new System.Uri("http://www.court.gov.il/NGCS.Web.Site/HomePage.aspx", System.UriKind.Absolute);
}
private void HandleRequest(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (checks < 1)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(HandleRequest);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetDetails);
}
caseNumber = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaCaseNumberTextBoxHT"];
caseDate = ((WebBrowser)sender).Document.All["Header1_CaseLocatorHeaderUC2_BamaMonthYearTextBoxHT"];
if (caseNumber != null && caseDate != null)
{
caseNumber.Focus();
System.Windows.Forms.SendKeys.Send("(5)");
System.Windows.Forms.SendKeys.Send("(6)");
System.Windows.Forms.SendKeys.Send("(5)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("{TAB}");
System.Windows.Forms.SendKeys.Send("(0)");
System.Windows.Forms.SendKeys.Send("(8)");
System.Windows.Forms.SendKeys.Send("(1)");
System.Windows.Forms.SendKeys.Send("(3)");
checks = 0;
System.Windows.Forms.SendKeys.Send("{ENTER}");
}
else
{
MessageBox.Show("No such case - enter a new one");
}
}
private void GetDetails(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(GetDetails);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(GetResults);
DetailsTag = webBrowser1.Document.All["_ctl0_caseDetailsGrid_row1_ct6_Imagebutton1"];
if (DetailsTag != null)
{
DetailsTag.InvokeMember("Click");
}
else
{
MessageBox.Show("Error - try another case!");
}
}
private void GetResults(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(GetResults);
HtmlElement DetailsStatus = webBrowser1.Document.All["_ctl7_caseStatusIDlbl"];
HtmlElement DetailsCourt = webBrowser1.Document.All["_ctl7_courtIDlbl"];
HtmlElement DetailsType = webBrowser1.Document.All["_ctl7_caseTypeIDlbl"];
HtmlElement DetailsAmount = webBrowser1.Document.All["_ctl7_claimAmountlbl"];
HtmlElement DetailsPrev = webBrowser1.Document.All["_ctl7_privilegeIDlbl"];
txtAmount.Text = DetailsAmount.InnerText;
txtCount.Text = DetailsCourt.InnerText;
txtPrev.Text = DetailsPrev.InnerText;
txtStatus.Text = DetailsStatus.InnerText;
txtType.Text = DetailsType.InnerText;
}
public void btnGet_Click(object sender, EventArgs e)
{
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(HandleRequest);
firstStep();
}
}
}
As said via comment, your approach for populating the textboxes is not too orthodox and, actually, is not working on my computer. The usual proceeding is relying on the SetAttribute function. Your code would become:
caseNumber.SetAttribute("value", "12283");
caseDate.SetAttribute("value", "03-10");
If I do that and then I use your inputTag.InvokeMember("Click"), the form is submitted (at least, no popup appears and the browser is redirected to a new page).

C# form instantly closing

All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
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;
namespace ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.

Saving values from datagridview

I am new to c#. I have been trying to add values from my datagrid to mysql but in vain and i really need your help. The values are automatically generated after a time interval of 1 sec and i need to insert them to the mysql in the same time interval. Here are the codes.
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 System.IO;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace BLIND_SHOPPING_SYSTEM
{
public partial class Form2 : Form
{
private DataTable m_TagDataTable = new DataTable("Tag List");
long passiveID = 0;
public Form2()
{
InitializeComponent();
this.m_TagDataTable.Columns.Add("TagID");
}
private void btn_GenerateID_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
public void timer1_Tick(object sender, EventArgs e)
{
if (passiveID < 10)
{
passiveID = passiveID + 1;
//listBox1.Items.Add(passiveID);
//this.m_TagDataTable.Columns.Add("TagID");
this.dataGridView1.DataSource = m_TagDataTable;
DataRow dr = m_TagDataTable.NewRow();
dr["TagID"] = passiveID;
m_TagDataTable.Rows.Add(dr);
}
else
// Application.Exit();
Console.ReadLine();
}
private void btn_Stop_Click(object sender, EventArgs e)
{
timer1.Enabled = false;
}
}
}
Please kindly help me.
You probably want to use a DataTableAdapter and specify the Update command, see here for some examples ;) http://msdn.microsoft.com/en-us/library/ms233819(v=vs.80).aspx

Categories