I'm having problem with print preview dialog. When I click on print preview, it doesn't show anything I print preview page. I have created a method to setup a preview print output. I can't figure out where did I miss !
below is 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;
namespace movieList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
// setup output
Font printFont = new Font("Arial", 14);
//print heading
e.Graphics.DrawString("Select Name", printFont, Brushes.Black, 100, 100);
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// terminate application
this.Close();
}
private void clearAllCategoriesToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear all the list of the category
// first we use dialog box for confirmation request
DialogResult confirmDialog = MessageBox.Show("Do you want to delete all category list ?","Clear Category List",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
if (confirmDialog == DialogResult.Yes)
{
// clearing the comboBox list
categoryComboBox.Items.Clear();
}
}
private void displayTheMovieCategoryCountToolStripMenuItem_Click(object sender, EventArgs e)
{
// count the number of category list
int listCountInteger = categoryComboBox.Items.Count;
MessageBox.Show("There are " + listCountInteger + " categories in the list", "ComboBox Count", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void removeACategoryToolStripMenuItem_Click(object sender, EventArgs e)
{
// remove a category name from list
// first checking if a category has selected
if (categoryComboBox.SelectedIndex == -1)
{
MessageBox.Show("Please Select a Category", "Wrong Selection", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
categoryComboBox.Items.RemoveAt(categoryComboBox.SelectedIndex);
}
}
private void addACategoryToolStripMenuItem_Click(object sender, EventArgs e)
{
// add a category to list
// first checking for no duplicate name
int indexNumberInteger=0;
bool foundNameBoolean=false;
if (categoryComboBox.Text == string.Empty)
{
//empty string has been entered
MessageBox.Show("Please Enter the new category Name !", "Empty Name", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
while(indexNumberInteger<categoryComboBox.Items.Count && !foundNameBoolean)
{
if (categoryComboBox.Text.ToUpper() == categoryComboBox.Items[indexNumberInteger++].ToString().ToUpper())
{
MessageBox.Show("This Category is already in the list, Please write a new one !", "Duplicate Data", MessageBoxButtons.OK, MessageBoxIcon.Error);
foundNameBoolean = true;
}
}
if (!foundNameBoolean)
{
// add new name to category
categoryComboBox.Items.Add(categoryComboBox.Text);
categoryComboBox.Text = string.Empty;
MessageBox.Show("Category has been updated !");
}
}
}
private void printTheCategoryListToolStripMenuItem_Click(object sender, EventArgs e)
{
// print preview
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
}
}
}
And preview picture :
Make sure your PrintPage event is wired up.
public Form1() {
InitializeComponent();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
}
Related
I created a little program to create a log file to record people's ID number, so far it runs good, no issues or errors, but recently I notice after running for three days it froze another program, until I force closed it. Can anyone take a look to the code to see if there is anything is wrong with it or to improve the code. Thank you.
The programs works with .NET Frameworks 3.5 and is for a Windows XP system, if is possible to make it work with a lower .NET Framework to reduce the installation of additional files.
MainWin form creates a fullscreen window to mask/cover some elements from other software. Is set as topmost to be always be on the top of everything. It has a transparent section with in a text file, then it minimize the window and finally activates a timer. When the timer finish, its maximaze the window again. It has a button to open the LoginWin form and a button to clear the data from the serieBox and return the cursor to the textbox.
LoginWin form is a window to input login information to open the LogFileWin form.
LogFileWin form is a window to read the saved data from the text file in a richTextBox, this data is from the MainWin form. It has a close button and a button to open FolderBrowserDialog to save the text file in another location or to a removable storage device.
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;
namespace LogSerie
{
public partial class MainWin : Form
{
public MainWin()
{
InitializeComponent();
}
private void MainWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void serieBox_KeyDown(object sender, KeyEventArgs e)
{
this.serieBox.MaxLength = 10;
if (e.KeyCode == Keys.Enter)
{
if ((serieBox.Text != ""))
{
if (serieBox.Text == "WLMANTO")
{
StreamWriter B = new StreamWriter("LogfileOperator.txt", true);
B.WriteLine(DateTime.Now + " " + label1.Text + " " + serieBox.Text);
B.Close();
serieBox.Clear();
this.WindowState = FormWindowState.Minimized;
timerManto.Enabled = true;
}
else
{
StreamWriter A = new StreamWriter("LogfileOperator.txt", true);
A.WriteLine(DateTime.Now + " " + label1.Text + " " + serieBox.Text);
A.Close();
serieBox.Clear();
this.WindowState = FormWindowState.Minimized;
timerOperador.Enabled = true;
}
}
}
}
private void timerOperador_Tick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
timerOperador.Enabled = false;
}
private void timerManto_Tick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
timerManto.Enabled = false;
}
private void logButton_Click(object sender, EventArgs e)
{
LoginWin openForm = new LoginWin();
openForm.ShowDialog();
}
private void borrarBut_Click(object sender, EventArgs e)
{
serieBox.Clear();
serieBox.Select();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace LogSerie
{
public partial class LoginWin : Form
{
public LoginWin()
{
InitializeComponent();
}
private void LoginWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void entrarBut_Click(object sender, EventArgs e)
{
if ((usuBox.Text != "") && (contraBox.Text != ""))
{
if ((usuBox.Text == "ADMIN") && (contraBox.Text == "PASS"))
{
LogFileWin openForm = new LogFileWin();
openForm.TopMost = true;
openForm.ShowDialog();
usuBox.Clear();
contraBox.Clear();
this.Close();
}
else
{
MessageBox.Show("Login Incorrect", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void cancelBut_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace LogSerie
{
public partial class LogFileWin : Form
{
public LogFileWin()
{
InitializeComponent();
}
private void LogFileWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void logfileButton_Click(object sender, EventArgs e)
{
string path = #"C:\LogfileOperator\LogfileOperator.txt";
StreamReader stream = new StreamReader(path);
string filedata = stream.ReadToEnd();
richTextBox1.Text = filedata.ToString();
stream.Close();
}
private void closeBut_Click(object sender, EventArgs e)
{
this.Close();
}
private void usbBut_Click(object sender, EventArgs e)
{
string fileName = "LogfileOperator.txt";
string sourcePath = #"C:\LogfileOperator";
using (FolderBrowserDialog ofd = new FolderBrowserDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileName);
sourcePath = Path.Combine(ofd.SelectedPath, fileInfo.Name);
File.Copy(fileName, sourcePath, true);
MessageBox.Show("Logfile Saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
If you're forced to use this old OS and old framework, you're going to have weird bugs like this. You can maybe work around it by reducing resource usage.
You're constantly creating new copies of your forms LoginWin and LogFileWin, which require OS resources. Instead create one instance of each form and re-use them.
There's also not any exception handling in your code, so you could have problems if files don't exist, or permissions change, or all sort of things. You need to have exception handling and that will give you more information about problems when they occur.
To re-use a form, create an instance as a private field in your class:
public partial class LoginWin : Form
{
// store the LogFileWin form so that we can re-use it
private LogFileWin _logFileWin;
public LoginWin()
{
InitializeComponent();
_logFileWin = new LogFileWin(); { TopMost = true; }
}
private void LoginWin_Load(object s, EventArgs e) { TopMost = true; }
private void entrarBut_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(usuBox.Text) ||
string.IsNullOrEmpty(contraBox.Text))
{
return;
}
if ((usuBox.Text == "ADMIN") &&
(contraBox.Text == "PASS"))
{
// add a reset function to the form
// that makes it ready to display again
_logFileWin.Reset();
// show the dialog
_logFileWin.ShowDialog();
usuBox.Clear();
contraBox.Clear();
this.Close();
}
else
{
MessageBox.Show("Login Incorrect",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void cancelBut_Click(object s, EventArgs e) { Close(); }
}
For exception handling:
public partial class LogFileWin : Form
{
public LogFileWin()
{
InitializeComponent();
}
private void LogFileWin_Load(object s, EventArgs e) { TopMost = true; }
// new function to reset the the dialog to be shown again
public void Reset() { richTextBox1.Text = string.Empty; }
private void logfileButton_Click(object s, EventArgs e)
{
var path = #"C:\LogfileOperator\LogfileOperator.txt";
try
{
// reading from a file can fail, so this
// needs to be wrapped in a try catch
using (var stream = new StreamReader(path))
{
richTextBox1.Text = stream.ReadToEnd();
}
}
catch (Exception ex)
{
var m = String.Format("Unable to read '{0}'; {1}",
path, ex.Message);
MessageBox.Show(message,
"File read error",
MessageBoxButtons.Ok,
MessageBoxIcon.Error);
}
}
private void closeBut_Click(object s, EventArgs e) { this.Close(); }
// we can re-use the folder browser dialog;
// don't need to create a new one every time
FolderBrowserDialog _ofd = new FolderBrowserDialog();
private void usbBut_Click(object sender, EventArgs e)
{
var sourceFileName = "LogfileOperator.txt";
var destFolder = #"C:\LogfileOperator";
var destFileName = string.Empty;
try
{
if (_ofd.ShowDialog() == DialogResult.OK)
{
destFileName = Path.Combine(_ofd.SelectedPath,
sourceFileName);
// every time you do anything with a
// file, it needs to be in a try/catch
// in case the file doesn't exist,
// or the user doesn't have permission.
File.Copy(sourceFileName, destFileName, true);
MessageBox.Show("Logfile Saved",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
// show a message to the user informing them
// of the error and why it occurred.
var m = string.Format("Copy '{0}' to '{1}' failed; {2}",
sourceFileName,
destFileName,
ex.Message);
MessageBox.Show(m,
"File copy error",
MessageBoxButtons.Ok,
MessageBoxIcon.Error);
}
}
}
First at all i am new at visual C#. I am trying to make a simple login form with only password login, but when i press button nothing happens. I want to check if there is a user in db which is online.
I dont know where i am making the mistake.
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 SportStat.Forme
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnUlaz_Click(object sender, EventArgs e)
{
ulaz();
}
private void ulaz()
{
if (txtPassword.Text == "")
{
MessageBox.Show("Morate upisati lozinku", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
return;
}
var sql = "select * from users where password='" + txtPassword.Text + "'";
var dt = sustav.puniDt(sql);
if (dt.Rows.Count == 0)
{
MessageBox.Show("Neispravna lozinka", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
if ((string)dt.Rows[0]["password"] != txtPassword.Text)
{
MessageBox.Show("Neispravna lozinka", "caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
sustav i = new sustav();
i.idUser = (int)dt.Rows[0]["idUser"];
i.pswd = (int)dt.Rows[0]["pswd"];
i.prezimeIme = (int)dt.Rows[0]["prezimeIme"];
i.idKlub = (int)dt.Rows[0]["idKlub"];
int count = i.pswd;
if (count == 1)
{
MessageBox.Show("Login Successful!");
this.Hide();
frmMain fm = new frmMain();
fm.Show();
}
this.Close();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
}
Can someone help me with this problem.
Can't comment, too low rep..
Try to put another button on the form and call ulaz(); from that new button.
Sometimes, if you delete button and add them again, or copy paste code, methods get autoassign another name.
For example:
private void btnUlaz_Click(object sender, EventArgs e)
{
ulaz();
}
private void btnUlaz_Click_1(object sender, EventArgs e)
{
ulaz();
}
First one wont work.
I don't know if this is the case in your problem but it's worth trying..
I have a program where a user fills in a form and hits calculate, then when the user hits summary it will show all the users that have entered in data. When more users enter data, they are simply added to the summary using the same lbl (lblUsers) the only problem I am having is being able to delete the most recent entry into the summary which would be the newest made label.
using System;
using System.Collections;
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 LifeInsurance
{
public partial class frmMain : Form
{
double commissionRate;
double insuranceAmount;
double totalAmount;
int numberOfCustomers;
double totalInsuranceDollars;
double totalCommission;
private void btnClearAll_Click(object sender, EventArgs e)
{
lblUsers.Text = "";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
insuranceAmount = int.Parse(txtInsuranceAmount.Text);
}catch (Exception)
{
MessageBox.Show("You must enter all details");
}
if(insuranceAmount>= 1000)
{
commissionRate = 0.005;
totalAmount = insuranceAmount * 0.005;
}
if (insuranceAmount >= 100000)
{
commissionRate = 0.0010;
totalAmount = insuranceAmount * 0.0010;
}
if (insuranceAmount >= 1000000)
{
commissionRate = 0.0015;
totalAmount = insuranceAmount * 0.0015;
}
totalInsuranceDollars += totalAmount;
totalCommission += commissionRate;
numberOfCustomers += 1;
lblUsers.Text += "Name: "+txtFirstName.Text +" "+ txtLastName.Text+"
"+ "Payout Amount: "+totalAmount+Environment.NewLine;
lblUsers.Text += "Total Policies: " + numberOfCustomers+" " + "Total
Insurance Dollars Earned: " + totalInsuranceDollars+" " + "Total
Commission Earned: " + totalCommission+Environment.NewLine;
}
private void btnSummary_Click(object sender, EventArgs e)
{
lblUsers.Visible = true ;
}
private void btnClear_Click(object sender, EventArgs e)
{
//remove one label
}
}
}
I'm sorry, if I understand correctly you want your Label to show all but the last entry when the user clicks "Summary" is that correct? So in your screenshot it shows 3 entries, but you want only 2 entries to be shown?
If so, see if this helps:
public static void btnSummary_Click(object sender, EventArgs e)
{
string currentText = lblUsers.Text;
int positionOfLastEntry = currentText.LastIndexOf("Name:");
string textWithoutLastEntry = currentText.Substring(0, positionOfLastEntry);
lblUsers.Text = textWithoutLastEntry;
lblUsers.Visible = true;
}
I've been trying to do this for a while now and just cannot get the code to execute the way I want it to. When running the program in C# visual studio, I click the submit button and instead of alerting me with errors because of the blank text boxes, it does nothing. I wanted to know how to execute the errorProvider or "errorCheck" in my code within the SUBMIT button (txtSubmit) so that it brings up the errors.
Here is the code 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.Windows.Forms;
using System.IO; //input output external files (.text)
using System.Text.RegularExpressions; //handles errors
using System.Xml;
namespace H1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
//Exits the application when pressed
Application.Exit();
}
private void btnClear_Click(object sender, EventArgs e)
{
//clears the fields when clicked
txtPid.Text = ""; //Patient Information Fields
txtPname.Text = "";
txtPphone.Text = "";
txtPaddress.Text = "";
txtPemail.Text = "";
txtPhysician.Text = ""; //Last visit fields
txtDate.Text = "";
txtReason.Text = "";
txtIid.Text = ""; //Insurance information fields
txtIcompany.Text = "";
txtIphone.Text = "";
txtIinsured.Text = "";
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string[] dat = new string[12]; //Declare new string array, 12 because 0 is included in count
dat[0] = txtPid.Text; //Patient Information Fields
dat[1] = txtPname.Text;
dat[2] = txtPphone.Text;
dat[3] = txtPaddress.Text;
dat[4] = txtPemail.Text;
dat[5] = txtPhysician.Text; //Last visit fields
dat[6] = txtDate.Text;
dat[7] = txtReason.Text;
dat[8] = txtIid.Text; //Insurance information fields
dat[9] = txtIcompany.Text;
dat[10] = txtIphone.Text;
dat[11] = txtIinsured.Text; //Array is now fully populated
StreamWriter sw = new StreamWriter("PatientInfo.txt"); //Declare a new writer
for(int i = 0; i < dat.Length; i++) //Iterate through the array
{
sw.WriteLine(dat[i]); //Writes the current position in a new line to specified file
}
sw.Close(); //Close our writer, don't need unused junk left open
}
private void Form1_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader("PatientInfo.txt"); //Specifies a new stream reader to read the file "File.dat"
String dat = sr.ReadToEnd(); //Reads the file until end and assigns it to the string "dat"
sr.Close(); //Close reader
dat = dat.Replace("\r", ""); //Removes all instances of carriage return, for handling/compatibility
string[] arr = dat.Split('\n'); //Splits the string into an array based on the new line character
}
private void txtPid_Validating(object sender, CancelEventArgs e)
{
// defines match
Match m = Regex.Match(txtPid.Text, #"\b[0-7]{7}\b"); //regular expressions
if (m.Success == false) //if does not match then provide below message
errorCheck.SetError(txtPid, "Patent I.D. must be 7 characters."); //error message
else errorCheck.SetError(txtPid, ""); //clears
}
private void txtPname_Validating(object sender, CancelEventArgs e)
{
if (txtPname.Text.Length < 3) //checks to see if there are less than 3 characters
{
errorCheck.SetError(txtPname, "Please enter the first and last name.");
}
else if (txtPname.Text.IndexOf(' ') == -1)
{
errorCheck.SetError(txtPname, "Must have both names seperated by a space.");
}
else errorCheck.SetError(txtPname, ""); //clears
}
private void txtPaddress_Validating(object sender, EventArgs e)
{
if (txtPaddress.Text == "")
{
errorCheck.SetError(txtPaddress, "You must enter the address.");
}
else errorCheck.SetError(txtPaddress, ""); //clears
}
private void txtPphone_Validating(object sender, CancelEventArgs e)
{
if (txtPphone.Text != "Valid")
{
errorCheck.SetError(txtPphone, "Telephone Number must be in proper format");
}
else errorCheck.SetError(txtPphone, "");
}
private void txtPemail_Validating(object sender, CancelEventArgs e)
{
if (txtPemail.Text == "") //checking for blanks
{
errorCheck.SetError(txtPemail, "You must enter an e-mail address.");
}
else if (txtPemail.Text == "#") //checking for #
{
errorCheck.SetError(txtPemail, "You must enter a valid e-mail address.");
}
else errorCheck.SetError(txtPemail, "");
}
private void txtIid_Validating(object sender, CancelEventArgs e)
{
Match m = Regex.Match(txtIid.Text, #"\b[0-7]{7}\b");
if (m.Success == false)
errorCheck.SetError(txtIid, "Insurance I.D. must be 7 characters.");
else errorCheck.SetError(txtIid, ""); //clear
}
private void txtIcompany_Validating(object sender, CancelEventArgs e)
{
if (txtIcompany.Text == "") //checking for blanks
{
errorCheck.SetError(txtIcompany, "You must enter an Insurance Company.");
}
else errorCheck.SetError(txtIcompany, "");
}
private void txtIphone_Validating(object sender, CancelEventArgs e)
{
if (txtIphone.Text != "Valid")
{
errorCheck.SetError(txtIphone, "Telephone Number must be in proper format");
}
else errorCheck.SetError(txtIphone, "");
}
private void txtIinsured_Validating(object sender, CancelEventArgs e)
{
if (txtIinsured.Text.Length < 4) // checking entry length
{
errorCheck.SetError(txtIinsured, "Please enter the first and last name.");
}
else if (txtIinsured.Text.IndexOf(' ') == -1) //checks for space
{
errorCheck.SetError(txtIinsured, "Must have both names.");
}
else errorCheck.SetError(txtIinsured, "");
}
private void txtDate_Validating(object sender, CancelEventArgs e)
{
if (txtDate.Text == "")
{
errorCheck.SetError(txtDate, "Must enter a correct date.");
}
else errorCheck.SetError(txtDate, "");
}
private void txtPhysician_Validating(object sender, CancelEventArgs e)
{
if (txtPhysician.Text == "") //checking for blanks
{
errorCheck.SetError(txtPhysician, "Must enter the Physician's name.");
}
else errorCheck.SetError(txtPhysician, "");
}
private void txtReason_Validating(object sender, CancelEventArgs e)
{
if (txtReason.Text == "")
{
errorCheck.SetError(txtReason, "Must enter a reason for visit.");
}
else errorCheck.SetError(txtReason, ""); //clears
}
}
}
I have this Form:
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 GatherLinks
{
public partial class ChangeLink : Form
{
public ChangeLink()
{
InitializeComponent();
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
}
}
And this code in Form1:
public void KeysValuesUpdate()
{
DialogResult dr = DialogResult.None;
using (var w = new StreamWriter(keywords_path_file))
{
crawlLocaly1 = new CrawlLocaly(this);
crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
if (FormIsClosing != true)
{
dr = crawlLocaly1.ShowDialog(this);
}
if (dr == DialogResult.OK)
{
if (LocalyKeyWords.ContainsKey(mainUrl))
{
LocalyKeyWords[mainUrl].Clear();
LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
}
else
{
LocalyKeyWords[mainUrl] = new List<string>();
LocalyKeyWords[mainUrl].Add(crawlLocaly1.getText());
}
Write(w);
ClearListBox();
}
if (dr == DialogResult.Cancel)
{
Write(w);
}
if (dr == DialogResult.None)
{
Write(w);
}
}
}
This KeysValuesUpdate() function is called here:
private void button2_Click(object sender, EventArgs e)
{
cl = new ChangeLink();
cl.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = cl.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
cl.Close();
}
else if (dr == DialogResult.OK)
{
label4.Text = cl.getText();
mainUrl = cl.getText();
if (!LocalyKeyWords.ContainsKey(mainUrl))
{
newUrl = true;
KeysValuesUpdate();
}
else
{
newUrl = false;
KeysValuesUpdate();
}
OptionsDB.set_changeWebSite(cl.getText());
cl.Close();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
When I click the button2 it's opening the new Form with a textbox and then inside I can type text.
Then I checking if the text inside already exist then newUrl is false or true.
Then when I click OK the OK button in the new Form then it's checking if the text I typed Contain/exist already or not.
I want that when the user type something in the textbox while he is typing if it's Contain/Exist the key then color the text in the textbox in Red one the user is keep typing and the text is not Contain/EXist color it back to Black but each time if the text in the textbox Contain/Exist already color it in Red and only if it's match case not if the text is inside other text:
This is in black:
For example : Danny hello all
But if I type in the textbox only: hello
Then the word hello will be in Red then if I kept typing after the hello then all the text in the textbox is Black if I delete the text and kept only the word hello then it will be Red again.
And that should be according to the code above and in realtime when im typing text in the textbox.
The new Form again with updated code with the textBox1 text changed event:
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 GatherLinks
{
public partial class ChangeLink : Form
{
Form1 f1;
public ChangeLink(Form1 f)
{
InitializeComponent();
f1 = f;
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (f1.mainUrl.Contains(textBox1.Text))
{
textBox1.ForeColor = Color.Red;
}
else
textBox1.ForeColor = Color.Black;
}
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
if (Regex.IsMatch(yourtext, #"\b" + textBox.Text + #"\b"))
{
textBox.ForeColor = Color.Red;
}
else
textBox.ForeColor = Color.Black;
}
Place your data containing variable name at the place of yourtext.
I have edited the answer. It is perfectly matching the whole words as you asked to do. To use Regex class, include System.Text.RegularExpressions namesapce.
You can implement textBox1 TextChanged event handler simply by defining a method
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textBox = sender as TextBox;
String text = textBox.Text;
if (SomeCheck(text))
{
textBox.ForeColor = Color.Red;
}
else
{
textBox.ForeColor = Color.Black;
}
}
and assigning method textBox1_TextChanged to OnTextChanged property of textBox