Make Button Enabled after bools are true - c#

I need make Button active if theese three bools are true
public bool isFileOpened = false;
public bool isDrive = false;
public bool isPrice = false;
They are becoming true after two textboxes are filled and
filePath string is not empty
private void textBox1_TextChanged(object sender, EventArgs e) {
drive = CheckIntInput(sender, "not valid");
if (drive != 0) {
isDrive = true;
}
}
private void textBox2_TextChanged(object sender, EventArgs e) {
price = CheckIntInput(sender, "not valid");
if (price != 0) {
isPrice = true;
}
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e) {
filePath = openFileDialog1.FileName;
label1.Text = filePath;
isFileOpened = true;
}
CheckIntInput method returning number from textBox or 0 if can`t convert string to number
And how i can make something like this:
if (isFileOpened && isDrive && isPrice) {
showButton.Enabled = true;
}
I want to make button enabled immediately after all three bools becomes true, and theese three fields can be inputted in different ways, like
textbox1
textbox2
openfiledialog1
or
textbox1
openfiledialog1
textbox2

There are multiple ways to do this, I'd use a property with a backing field, like this:
public bool IsFileOpened
{
get { return _isFileOpened; }
set
{
_isFileOpened = value;
UpdateShowButton();
}
}
public bool IsDrive
{
get { return _isDrive; }
set
{
_isDrive = value;
UpdateShowButton();
}
}
public bool IsPrice
{
get { return _isPrice; }
set
{
_isPrice = value;
UpdateShowButton();
}
}
private void UpdateShowButton()
{
if (IsPrice && IsDrive && IsFileOpened)
showButton.Enabled = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
drive = CheckIntInput(sender, "not valid");
if (drive != 0)
{
IsDrive = true;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
price = CheckIntInput(sender, "not valid");
if (price != 0)
{
IsPrice = true;
}
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
filePath = openFileDialog1.FileName;
label1.Text = filePath;
IsFileOpened = true;
}
Actually I renamed it as well, so you have to use the properties with the capitalized starting letter. Now, everytime a property is updated, it checks wether to set the showButton enabled or not.
Here you can read more about fields and properties (with backing fields as well).

Related

Can't hide labels and text boxes when button is checked

When salaried button is checked, change label "Hour Pay: " to "Salary" and hide the labels and text boxes below it. When Hourly button is checked, return everything to its initial form.
My main issue is when i execute code it does not hide labels and text boxes.
private void addButton_Click(object sender, EventArgs e)
{
}
private void icontype_CheckedChanged(object sender, EventArgs e)
{
if (salariedRadioButton.Checked == true)
{
hourLabel.Visible = false;
}
else if (hourlyRadioButton.Checked == true)
{
hourLabel.Visible = true;
}
}
private void hourTextBox_TextChanged(object sender, EventArgs e)
{
try
{
weekTextBox.Text =(float.Parse(hourTextBox.Text)40).ToString();
}
catch
{
}
try
{
yearTextBox.Text = (float.Parse(weekTextBox.Text) 52).ToString();
}
catch
{
}
}
I'm not sure what's your expected result, for the hide part, I think you can try this, thanks.
public Form1()
{
InitializeComponent();
this.salariedRadioButton.CheckedChanged += icontype_CheckedChanged;
this.hourlyRadioButton.CheckedChanged += icontype_CheckedChanged;
}
private void icontype_CheckedChanged(object sender, EventArgs e)
{
if (salariedRadioButton.Checked == true)
{
hourLabel.Visible = false;
weekTextBox.Visible = false;
}
else if(hourlyRadioButton.Checked == true)
{
hourLabel.Visible = true;
weekTextBox.Visible = true;
}
}

cannot implicitly convert type void to int c#

Hello So I am making a text editor and have two functions I call when clicking on different buttons in my GUI. So I call my "NewTextbutton" function in "CloseToolStripMenuItem" function. What I want is if the user clicks on cancel my program should not close.I though I can have a returned value from the function and then with if statment check if the user clicked on cancel or not. But I get error that I cannot convert Void to int. Can anyone please help. Thanks.
private int NewTextbutton_Click(object sender, EventArgs e)
{
if (TextBox.TextLength==0)
{
TextBox.Clear();
return 0;
}
else
{
if (this.Text.Contains("*"))
{
var result = MessageBox.Show("Do you want to save changes to the document?",
"Texteditor",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
SaveTextbutton.PerformClick();
TextBox.Clear();
this.Text = $"Texteditor dok1.txt";
P = "";
return 0;
}
else if (result == DialogResult.Cancel)
{
return 1;
}
else
{
TextBox.Clear();
return 0;
}
}
TextBox.Clear();
this.Text = $"Texteditor dok1.txt";
P = "";
return 0;
}
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
int a = NewTextbutton.PerformClick(); //here is the error "cannot convert void to int"
if (a == 1)
{
MessageBox.Show("operation Canceled");
}
else
{
Application.Exit();
}
}
Indeed, an event handler usually returns void not int, so you cannot use PerformClick to get a return value.
You can refactor this way, for instance :
private int CheckWhatToDo()
{
// all the code that was in NewTextbutton_Click(object sender, EventArgs e)
}
private void NewTextbutton_Click(object sender, EventArgs e) {
CheckWhatToDo();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
int a = CheckWhatToDo();
if (a == 1)
{
MessageBox.Show("operation Canceled");
}
else
{
Application.Exit();
}
}

C# - Windows Application - Saving List

I have made a simple TO-DOs program that gets input from a text box then place it in another text box. With tick boxes next to it,
this is all fine except i Cannot save the list eg. the item and if it's finished or not.
Please could anyone help me be able to save this list of items.
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 TO_DOs
{
public partial class Form1 : Form
{
private bool text1, text2, text3, text4, text5, text6, text7, text8;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (text1 == false)
{
textBox2.Text = textBox1.Text;
}
else if (text2 == false)
{
textBox3.Text = textBox1.Text;
}
else if (text3 == false)
{
textBox4.Text = textBox1.Text;
}
else if (text4 == false)
{
textBox5.Text = textBox1.Text;
}
else if (text5 == false)
{
textBox6.Text = textBox1.Text;
}
else if (text6 == false)
{
textBox7.Text = textBox1.Text;
}
else if (text7 == false)
{
textBox8.Text = textBox1.Text;
}
else if (text8 == false)
{
textBox9.Text = textBox1.Text;
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
text1 = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
text2 = true;
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
text4 = true;
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
text5 = true;
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
text6 = true;
}
private void textBox8_TextChanged(object sender, EventArgs e)
{
text7 = true;
}
private void textBox9_TextChanged(object sender, EventArgs e)
{
text8 = true;
}
}
}
I would do it like this:
Create a class to store your values in:
public class ListEntry
{
public string Text { get; set; }
public bool Finished { get; set; }
}
Then I would create 2 Methods:
public List<ListEntry> UI_To_List(); //Create UI from your saved file
public void List_To_UI(List<ListEntry> entries); //Process your UI
Now it's your choice on how to store your list.
You could store it as JSON or XML.
A few recommendations:
I would create a UserControl for your TextBox + CheckBox
Display the 'List of UserControls' in a FlowLayoutPanel
=> then you can process the FlowLayoutPanel.Controls List.
This will make your List dynamically size to an 'unlimited' amount of items.
Short example:
Create a UserControl (Rightclick project for that):
Add these 2 methods to the code of your UserControl (F7 / rightclick => View Code):
public void SetText(string text)
{
//Set the Text of your TextBox in the UserControl:
textBox1.Text = text;
}
public void SetFinished(bool finished)
{
//Set the Checked of your CheckBox in the UserControl:
checkBox1.Checked = finished;
}
In your MainForm add an FlowLayoutPanel (from ToolBox).
Add your Data like this (using class from above):
/// <summary>
///
/// </summary>
/// <param name="entries">You will get them from loading your previously saved file</param>
public void CreateUI(List<ListEntry> entries)
{
foreach (ListEntry entry in entries)
{
//Create new instance of your UserControl
TaskView view = new TaskView();
view.SetFinished(entry.IsFinished);
view.SetText(entry.Text);
//Add that to your UI:
this.flowLayoutPanel1.Controls.Add(view);
}
}
The result will look like this:
I'm not sure what exactly it is that you want to save in a list... but here's just a tip when checking conditions, instead of using if (text1 == false), simply do if (!text1) as this means "is not true" because by default if (text1) will return true.
private void button1_Click(object sender, EventArgs e)
{
if (!text1)
{
textBox2.Text = textBox1.Text;
}
else if (!text2)
{
textBox3.Text = textBox1.Text;
}
// Left out the rest of the else ifs
}
You are casting textboxes wrong. For example when you change textBox4, you gave text3 true.
private void textBox4_TextChanged(object sender, EventArgs e)
{
text3 = true;
}
Then you cast
TextBox4.Text = TextBox1.Text;
It changes TextBox4.Text to TextBox1.Text.
You probably want to save TextBox4.Text here at TextBox1.Text so you sould change all if blocks like that. So you have to give only one "true" function for changed textBox sign and change if blocks
if(text(boolNum))
TextBox1.Text = TextBox(Number).Text;
Just swap them and try like that.
If you want to save another thing by another way. You have to be more spesific.
You can use a CheckedListbox to hold all tot actions.
You can then tick the itemsand for instance in the OK button you include a save action:
foreach(var item in MyCheckedListbox.CheckedItems)
{
Console,WriteLine(item.Text);
}
Lets see the answer from Felix D. He tells you exactly how to create a class and save the items into it. But now you only have a List that will be available as long as your software is running. You still need to save it somewhere on your desktop.
Lucky for you, you got a really simple pattern.
string; boolean
So how about you make it yourself simple? Just create a textfile and write your entries, as example in a csv marked with a ; for every information?
Example:
class Program
{
public class tmpClass
{
public string Text;
public bool tick;
}
public List<tmpClass> tmpList = new List<tmpClass>();
static void Main(string[] args)
{
//Stuff
}
public void WriteToFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamWriter tmpWriter = new StreamWriter(tmpTextFilePath))
{
string tmpTextToWrite = String.Empty;
for (int i = 0; i < tmpList.Count; i++)
{
tmpClass tmpEntry = tmpList[i];
tmpTextToWrite += tmpEntry.Text + ";" + tmpEntry.tick;
}
tmpWriter.WriteLine(tmpTextToWrite);
}
//Now we wrote a text file to you desktop with all Informations
}
public void ReadFromFile()
{
string tmpTextFilePath = #"C:\User\Desktop\SaveText.txt";
using (StreamReader tmpReader = new StreamReader(tmpTextFilePath))
{
string tmpText = tmpReader.ReadLine();
string tmpInput = String.Empty;
tmpClass tmpClass = new tmpClass();
int i = 0;
foreach (char item in tmpText)
{
if(item.Equals(";".ToCharArray()))
{
if (i == 0)
{
tmpClass.Text = tmpInput;
i = 1;
tmpInput = String.Empty;
}
else
{
if (tmpInput == "True")
tmpClass.tick = true;
else
tmpClass.tick = false;
i = 0;
tmpInput = String.Empty;
tmpList.Add(tmpClass);
}
}
tmpInput += item;
}
}
}
}
This should simply write a txt File to your desktop with your information and read one and save it to your list.

Validate one method C#

If I have one validating method Method1 which returns e.Cancel true or false, and which looks like this:
private void textBox1_Validating_1(object sender, CancelEventArgs e)
{
ErrorProvider errorProvider = new ErrorProvider();
bool isEmpty = String.IsNullOrEmpty(textBox1.Text);
if (isEmpty)
{
e.Cancel = true;
errorProvider.SetError(textBox1, "txt");
}
else
{
e.Cancel = false;
errorProvider.SetError(textBox1, "");
}
}
And I want to get the result of validation, in my other method, here:
private void button4_Click(object sender, EventArgs e)
{
//bool passed = this.Validate(textBox1_Validating_1);
if (passed == false) return;
I would want something like this:
bool passed = this.Validate(textBox1_Validating_1);
Only to validate this one method. How do I do it?
I am able to do it like this:
bool passed = this.ValidateChildren();
if (passed == false) return;
But if I do that, then I validate all my methods, but I one want to validate just this one Method1
How can I accomplish this?
I will suggest to create a separate method for validation and call it on submit. Try this :
private void SubmitButton_Click(object sender, EventArgs e)
{
if (ValidateControls()==0)
{
//Form is validated
}
}
int ValidateControls()
{
int flag = 0;
errorProvider1.Clear();
if (txtAge.Text.Trim() == String.Empty)
{
errorProvider1.SetError(txtAge, "Age is required");
flag = 1;
}
............................................
............................................
// validate all controls
............................................
............................................
if (txtSalary.Text.Trim() == String.Empty)
{
errorProvider1.SetError(txtSalary, "Salary is required");
flag = 1;
}
return flag;
}
public bool IsValidated()
{
return !String.IsNullOrEmpty(textBox1.Text);
}
private void button4_Click(object sender, EventArgs e)
{
bool passed = IsValidated();
}
Something like this?
var cnclEvent = new CancelEventArgs();
textBox1_Validating_1(null, cnclEvent);
if (cnclEvent.Cancel) return;

Set Properties and create events for a user control

I'm creating a web user control in asp.net using C# in which i can select a date from a calendar and display it in a textbox. when i select a date from the calender it has to be displayed in the textbox.
now i need to set my own properties by which i can select datetime patterns in cs codefile. for example
usercontrol1.dd-mm-yyyy.
this is one example. now i want all the datetime patterns of "en-us". when i use that usercontrol in another page i want to set any of the properties(datetime patterns) to that control. please help me!!!
i tried this coding but no use... plz review it and give me solution
public partial class DateControl : System.Web.UI.UserControl
{
string dateformat;
public string Dateformat
{
get { return dateformat;}
set { dateformat = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PageLoad();
lnlbtnChangeDate.Visible = false;
ddlDateFormat.Visible = false;
Calendar.Visible = false;
}
lblError.Visible = false;
}
public void PageLoad()
{
if (txtBoxDate.Text != "")
{
Calendar.Visible = false;
}
CultureInfo ci = new CultureInfo("fr-fr");
string[] format = ci.DateTimeFormat.GetAllDateTimePatterns();
foreach (string i in format)
{
ddlDateFormat.Items.Add(i);
}
}
protected void lnkbtnPickDate_Click(object sender, EventArgs e)
{
Calendar.Visible = true;
lnlbtnChangeDate.Visible = true;
ddlDateFormat.Visible = false;
}
public void Calendar_SelectionChanged1(object sender, EventArgs e)
{
txtBoxDate.Text = Calendar.SelectedDate.ToShortDateString();
}
protected void ddlDateFormat_SelectedIndexChanged(object sender, EventArgs e)
{
txtBoxDate.Text = Calendar.SelectedDate.ToString(ddlDateFormat.SelectedValue.ToString());
}
protected void lnlbtnChangeDate_Click(object sender, EventArgs e)
{
Calendar.Visible = false;
if (txtBoxDate.Text == "")
{
lblError.Visible = true;
}
else
{
lblError.Visible = false;
lnlbtnChangeDate.Visible = true;
ddlDateFormat.Visible = true;
}
}
protected void lnkbtnClear_Click(object sender, EventArgs e)
{
txtBoxDate.Text = "";
Calendar.Visible = false;
lnlbtnChangeDate.Visible = false;
ddlDateFormat.Visible = false;
lblError.Visible = false;
}
i said that i want set properties for my user control and create events for that.... plz help me
Not sure I get it right at the question is not very clear, but anyway :
You could just create Properties for you user controls, and assign Enums to them
public enum My_UserControl_DateFormats
{
YYYYMMDD = 1,
YYYYMMDDHH = 2,
YYYYMMDDHHmmSS = 3
}
And in the setter code of your properties handle the logic to assign the Date Format (For Example) according to the enum value (using switch/case)
It's one among many possibilities.

Categories

Resources