I try to display crystal report in Report.aspx. so for this first i create class "``report_class` and in that class i create function like this:
using cookies
in webform2 i try this
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue, ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page, string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
then on button click
protected void Button6_Click(object sender, EventArgs e)
{
try
{
string datef = string.Empty;
setCookiesValue(this, "fromdate", "todate","regiondrop", ref ret);
report_class r = new report_class();
Report_Detail report = new Report_Detail();
Response.Redirect("Reports.aspx");
}
catch
{
Label4.Visible = true;
}
}
and in reports.aspx
protected void Page_Load(object sender, EventArgs e)
{
Report_Detail report = new Report_Detail();
report_class r = new report_class();
string date_f = getCookies(this, "fromdate");
string date_t = getCookies(this, "todate");
string drop_r = getCookies(this, "regiondrop");
r.Bindreport_class(report, Convert.ToDateTime(date_f),
Convert.ToDateTime(date_t), Convert.ToString(drop_r));
CrystalReportViewer1.ReportSource = report;
CrystalReportViewer1.DataBind();
}
but this show error
Error 8 No overload for method 'setCookiesValue' takes 5 arguments
Error 3 The name 'getCookies' does not exist in the current context
You just need to pass the value from for Example form1 to form2:
Do it this way:
FORM2
public partial class Form2 : Form
{
public static Label lblvar= null;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
}
FORM1:
public partial class Form1 : Form
{
public Form1()
{
Form2.lblvar = lblvarinform1;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
lblvarinform1.Text = txtdatepicker.Text;
Form2.lblvar.Text = lblvarinform1.Text;
}
}
USING COOKIES:
public static bool setCookiesValue(Page page, string cookiesName, string cookiesValue,ref string ermsg)
{
if (cookiesValue.Trim().Length < 1)
{
ermsg = "cookies empty";
return false;
}
HttpCookie clearCookies = page.Request.Cookies[cookiesName];
clearCookies[cookiesName] = cookiesValue;
clearCookies.Expires = DateTime.Now.AddDays(1d);
page.Response.Cookies.Add(clearCookies);
return true;
}
public static String getCookies(Page page,string cookiesName)
{
try
{
HttpCookie GetCookies = page.Request.Cookies[cookiesName];
return GetCookies[cookiesName].ToString();
}
catch (Exception er)
{
return string.Empty;
}
}
using the function above:
set cookies new value:
string ret = string.Empty;
setCookiesValue(this,"yourcookiesname","thisisyourdatevaue_or_any",ref ret);
get cookies value in another form:
string getval = getCookies(this,"yourcookiesname");
Related
So my program is a simple form that a user has to read, agree to the terms, and close the window. When the user closes the window it takes their login name and date / time, writes it to a txt file and exits. When the program loads, I want it to check the file for the existing username. If it finds the username, check the date on which it was recorded and if it was within 6 months exit the program. If it was recorded more than 6 months ago, run the program. Obviously, if the reading of the file doesn't find the username I want the program to run as well. Here is my code so far -
namespace EUSAA
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
txtDateTime.Text = DateTime.Now.ToString();
txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
btnClose.Visible = false;
chkAgree.Visible = true;
rtbSecurityAwareness.LoadFile("Security Awareness.rtf");
}
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
if (chkAgree.Checked)
{
btnClose.Visible = true;
}
else btnClose.Visible = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
using (StreamWriter sw = File.AppendText(#"I:\Security Awareness Signed Users\Signed Users.txt"))
{
sw.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name + "\t" + DateTime.Now.ToString());
}
Environment.Exit(0);
}
This isn't a code writing site; but I was feeling generous. The following class encapsulates storing and retrieving the latest agreement for the current user.
public class AgreementRepository
{
private const string FileLocation = #"I:\Security Awareness Signed Users\Signed Users.txt";
private const char Separator = '\t';
public void AppendAgreementForCurrentUser()
{
string currentUser = GetCurrentUser();
using (StreamWriter sw = File.AppendText(FileLocation))
{
sw.WriteLine($"{currentUser}{Separator}{DateTime.Now:O}");
}
}
public DateTime? GetLastAgreementForCurrentUser()
{
string currentUser = GetCurrentUser();
if (File.Exists(FileLocation) == false)
{
return null;
}
var lastAgreement = File.ReadLines(FileLocation)
.Select(x => x.Split(Separator))
.Where(x => x.Length == 2 && string.Equals(x[0], currentUser, StringComparison.CurrentCultureIgnoreCase))
.Select(x => GetDateTime(x[1]))
.Max();
return lastAgreement;
}
private static DateTime? GetDateTime(string input)
{
DateTime result;
if (DateTime.TryParse(input, out result))
{
return result;
}
return null;
}
private static string GetCurrentUser()
{
return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
}
To use this, your form would become...
public partial class frmMain : Form
{
private readonly AgreementRepository _agreementRepository;
public frmMain()
{
_agreementRepository = new AgreementRepository();
InitializeComponent();
txtDateTime.Text = DateTime.Now.ToString();
txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
btnClose.Visible = false;
chkAgree.Visible = true;
rtbSecurityAwareness.LoadFile("Security Awareness.rtf");
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
var lastAgreement = _agreementRepository.GetLastAgreementForCurrentUser();
// NOTE: The following condition deals with the fact that lastAgreement could be null
if (lastAgreement > DateTime.Now.AddMonths(-6))
{
Close(); // or Environment.Exit; depends what you need
}
}
private void chkAgree_CheckedChanged(object sender, EventArgs e)
{
btnClose.Visible = chkAgree.Checked; // simplification of your posted code
}
private void btnClose_Click(object sender, EventArgs e)
{
_agreementRepository.AppendAgreementForCurrentUser();
Environment.Exit(0); // Would 'Close()' be enough?
}
Hope this helps
This question already has an answer here:
How to open new form, pass parameter and return parameter back
(1 answer)
Closed 4 years ago.
frmPlaceOrder is my form1. I need to pass the firstName, lastname and Address from this form to the second one which will do the other functions. I don't know how to do that.
namespace Lab1_OrderCake
{
public partial class frmPlaceOrder : Form
{
public static CustomerInformation customer;
public static Address address;
public frmPlaceOrder()
{
InitializeComponent();
customer = new CustomerInformation(txtFName.Text, txtLName.Text);
address = new Address(txtAddress.Text, txtCity.Text, txtPC.Text, txtProvince.Text);
}
private void btnPlaceOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
if (txtFName.Text == "")
{
MessageBox.Show("Please enter first name", "Data Missing");
txtFName.Focus();
return;
}
if (txtLName.Text == "")
{
MessageBox.Show("Please enter Last name", "Data Missing");
txtLName.Focus();
return;
}
else
{
frmCakeOrder newCust = new frmCakeOrder();
this.Hide();
newCust.ShowDialog();
this.Close();
}
}
}
}
The second form; after the first one has been filled out needs to take the values from form1 and display it with the other values(frmCakeOrder values) in the second form. It needs to be seen in the View and Order events when i click it.
here is the Second form:
namespace Lab1_OrderCake
{
public partial class frmCakeOrder : Form
{
Order cakeOrder;
public List<Cake> cakeList;
public frmCakeOrder()
{
InitializeComponent();
cmbTraditionalCake.SelectedIndex = 0;
cakeOrder = new Order();
gbCustomCake.Visible = false;
this.Size = new Size(700,360);
cakeList = new List<Cake>();
}
private void bttnOrder_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Confirm Order", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlgMsg == DialogResult.Yes)
{
MessageBox.Show(cakeOrder.PrintConfirmation());
}
else
{
MessageBox.Show ("The order has not been placed");
}
bttnReset.Focus();
cakeOrder.ClearCart();
}
private void radCustom_CheckedChanged(object sender, EventArgs e)
{
if (radCustom.Checked)
{
cmbTraditionalCake.Enabled = false;
gbCustomCake.Visible = true;
}
else
{
cmbTraditionalCake.Enabled = true;
gbCustomCake.Visible = false;
}
}
private void btnView_Click(object sender, EventArgs e)
{
DialogResult dlgMsg;
cakeOrder.NumOfCakes=1;
dlgMsg = MessageBox.Show(cakeOrder.ToString(), "Your order: ", MessageBoxButtons.YesNo , MessageBoxIcon.Information);
if (dlgMsg == DialogResult.No)
{
cakeOrder.ClearCart();
MessageBox.Show("Please enter and confirm your order!");
}
private void btnAdd_Click(object sender, EventArgs e)
{
if (radCustom.Checked)
{
string flavour, occasion;
flavour = occasion = "";
int layers;
//for flavor
if (radBanana.Checked)
flavour = "Banana";
else if (radChocolate.Checked)
flavour = "Chocolate";
else if (radVanilla.Checked)
flavour = "Vanilla";
if (radTier2.Checked)
layers = 2;
else if (radTier3.Checked)
layers = 3;
else
layers = 1;
if (radGraduation.Checked)
occasion = radGraduation.Text.TrimStart(new char[] { '&' });
else if (radWedding.Checked)
occasion = radWedding.Text.TrimStart(new char[] { '&' });
else occasion = radAnniversary.Text.TrimStart(new char[] { '&' });
cakeOrder.AddCake(new Custom(flavour, occasion, layers));
}
else
{
cakeOrder.AddCake(new Traditional(cmbTraditionalCake.SelectedItem.ToString()));
}
cakeList.Add(cakeOrder);
}
}
}
There are many ways to do this. Try it this way.
private void btnPlaceOrder_Click(object sender, EventArgs e) {
string fname = textBox1.Text;
frmCakeOrder frm = new frmCakeOrder(textBox1.Text);
frm.Show();
}
And in frmCakeOrder,
public frmCakeOrder(string fname) {
InitializeComponent();
textBox1.Text = fname;
}
You can pass the data in the constructor:
public class Form1: from{
//constructor
public void Form1(){
}
public void button_click(){
//Get the data
var firstName = textFirstName.text;
var secondName= textSecondName.text;
var address= textAddress.text;
//Pass the data on the constructor of Form2
Form2 f2 = new Form2(firstName,secondName, address);
f2.show();
}
}
public class Form2: Form{
//constructor with data or parameters
public void Form2(string firstName, string lastName, string Address){
//do dosomething with the data
txtFirstName.text = firstName;
}
}
*sorry if it has sintaxys errors.... but thats the idea.
I have an user control calling a method on my main form and this method should enable a button (by default this button is disabled) on the same form, but it's not working.
private void button1_Click(object sender, EventArgs e)
{
Form1 fr = new Form1();
fr.login(textBox1.Text, textBox2.Text);
}
And here is my method
public void login(string username, string password)
{
Connect();
sendMessage("LoginAction,Username=" + username + "UserPassword=" + password);
}
Here is where the button is enabled
private void commandInterpreter(string Message)
{
if(Message.Contains("LoginSuccess,") == true)
{
name = Message.Remove(Message.IndexOf("LoginSuccess,Name="), 18);
Bt2En = true;
}
}
Here is where I'm exposing my button properties:
public bool Bt2En
{
get { return button2.Enabled; }
set { button2.Enabled = value; }
}
I solved my problem doing this, these are my methods from Form1:
public void login()
{
Connect();
Login lg = this.lg;
string username = lg.Username;
string password = lg.Password;
MessageBox.Show(username + "\n" + password);
}
private void button1_Click(object sender, EventArgs e)
{
login();
}
And this one is from my user control:
public string Username
{
get { return textBox1.Text; }
}
public string Password
{
get { return textBox2.Text; }
}
Thanks Steve and Bradley Uffner for help and everyone who tried. I'm posting the answer for who has the same problem.
Bt2En is a property but You use such as methods.
public void bt2En(bool flag)
{
if(flag)
button.Enable=true;
}
I have to send the value of 2 TextBoxes from FormB when I clic on the "validate buton" to the datagridView in FormA;this is what I try to code:
FormB:
namespace RibbonDemo.Fichier
{
public partial class NvFamillImmo : Form
{
public event BetweenFormEventHandler BetweenForm;
SqlDataAdapter dr;
DataSet ds = new DataSet();
string req;
public NvFamillImmo()
{
InitializeComponent();
affich();
}
private void button2_Click(object sender, EventArgs e) //the validate buton
{
if (BetweenForm != null)
BetweenForm(textBox1.Text, textBox2.Text);
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.amortissementFiscalTableAdapter.FillBy(this.mainDataSet.amortissementFiscal);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
}
}
and this is FormA:
namespace RibbonDemo.Fichier
{
public delegate void BetweenFormEventHandler(string txtbox1value, string txtbox2value);
public partial class FammileImm : Form
{
private NvFamillImmo nvFamillImmo;
public FammileImm()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
NvFamillImmo frm2 = new NvFamillImmo();
frm2.BetweenForm += frm2_BetweenForm;
frm2.ShowDialog();
}
void frm2_BetweenForm(string txtbox1value, string txtbox2value)
{
//dataGridView1.Refresh();
String str1 = nvFamillImmo.textBox1.Text.ToString();
this.dataGridView1.Rows[0].Cells[0].Value = str1;
}
}
}
EDIT:I filled the method frm2_BetwwenForm but now I get a problem in reference
thanks for Help
No Need to create event for that. you can create properties in second form where you want to send value from existing form. for example if you have two forms FormA and FormB then FormB should contains properties like Value1 and Value2.
//FormB
public class FormB :Form
{
public string Value1{get; set;}
public string Value2{get; set;}
}
Now you can assign value into both properties from FormA.
//FormA
public void button1_click(object sender, EventArgs e)
{
FormB myForm = new FormB();
myForm.Value1 = textBox1.Text;
myForm.Value2 = textBox1.Text;
myForm.Show();
}
Then you can get both textboxes value into FormB. You can handle value into Form Load event
//FormB
public void FormB_Load(object sender, EventArgs e)
{
string fromTextBox1 = this.Value1;
string formTextBox2 = this.Value2;
}
If the FormB is already loaded and want to send value from FormA then create a method UpdateValues() and modify the properties to call that method.
//FormB
string _value1 = string.Empty;
public string Value1
{
get { return _value1; }
set {
_value1 = value;
UpdateValues();
}
}
string _value2 = string.Empty;
public string Value1
{
get { return _value2; }
set {
_value2 = value;
UpdateValues();
}
}
private void UpdateValues()
{
string fromTextBox1 = this.Value1;
string fromTextBox2 = this.Value2;
}
and Assign the values in FormB.Value1 and FormB.Value2 properties from FormA.
//FormA
FormB myForm = new FormB();
public void button1_click(object sender, EventArgs e)
{
if (myForm != null && myForm.IsDisposed == false)
{
myForm.Value1 = textBox1.Text;
myForm.Value2 = textBox1.Text;
}
}
When the value is updated from FormA then UpdateValues() method will be called.
I created a program that monitors what happens to the files inside a directory. For example if I add a new file, it shows the path and the name of the new file. Though I coded it in Windows Forms, I want to change it to a Console Application so that it shows the results on the console
My question is that how can I browse a folder using a console?
any ideas thanks in advance
The Windows Forms code is below:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
button1.Enabled = false;
button2.Enabled = true;
directoryPath = folderBrowserDialog1.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (Directory.Exists(directoryPath))
{
textbox_append("monitor opened");
filesList = Directory.GetFiles(directoryPath);
timer1.Start();
}
else
{
MessageBox.Show("folder does not exist.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error." + ex.Message);
}
}
this is my whole code
namespace emin_lab2_Csharp
{
public partial class Form1 : Form
{
public string directoryPath;
string[] filesList, filesListTmp;
IFileOperation[] opList = { new FileProcByExt("jpeg"),
new FileProcByExt("jpg"),
new FileProcByExt("doc"),
new FileProcByExt("pdf"),
new FileProcByExt("djvu"),
new FileProcNameAfter20()
};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
button1.Enabled = false;
button2.Enabled = true;
directoryPath = folderBrowserDialog1.SelectedPath;
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
if (Directory.Exists(directoryPath))
{
textbox_append("monitor opened");
filesList = Directory.GetFiles(directoryPath);
timer1.Start();
}
else
{
MessageBox.Show("Такой папки нету.");
}
}
catch (Exception ex)
{
MessageBox.Show("Error." + ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
filesListTmp = Directory.GetFiles(directoryPath);
foreach (var elem in Enumerable.Except<string>(filesListTmp, filesList))
{
textbox_append(elem);
foreach (var op in opList)
{
if (op.Accept(elem)) { op.Process(elem); textbox_append(elem + " - action is performed on the file"); }
}
}
filesList = filesListTmp;
}
public void textbox_append(string stroka)
{
textBox1.AppendText(stroka);
textBox1.AppendText(Environment.NewLine);
}
interface IFileOperation
{
bool Accept(string fileName);
void Process(string fileName);
}
class FileProcByExt : IFileOperation
{
string extName;
string folderName;
public FileProcByExt(string ext = "")
{
extName = ext;
folderName = extName.ToUpper();
}
public bool Accept(string fileName)
{
bool res = false;
if (Path.GetExtension(fileName) == "." + extName) res = true;
return res;
}
public void Process(string fileName)
{
Directory.CreateDirectory(Path.Combine(Path.GetDirectoryName(fileName),
folderName));
File.Move(fileName,
Path.Combine(Path.GetDirectoryName(fileName),
folderName,
Path.GetFileName(fileName)));
}
}
class FileProcNameAfter20 : IFileOperation
{
public bool Accept(string fileName)
{
return Path.GetFileNameWithoutExtension(fileName).Length > 20;
}
public void Process(string fileName)
{
int cnt = Path.GetFileNameWithoutExtension(fileName).Length;
File.Copy(fileName,
Path.Combine(Path.GetDirectoryName(fileName),
"longname_" + cnt + Path.GetExtension(fileName)));
}
}
}
}
First, you need to add reference to System.Windows.Forms
Second, add STAThread attribute to your method.
For example:
using System;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.ShowDialog();
Console.Write(ofd.FileName);
}
}
}