String does contain a definition for isnullorwhitespace - c#

Please help me in my system. I don't know whats the problem with isnullorwhitespace:
My error for this is:
"string does contain a definition for isnullorwhitespace"
What is my other option for isnullorwhitespace?
private void btnAdd_Click(object sender, EventArgs e)
{
int age = int.Parse(txtage.Text);
if (string.IsNullOrWhiteSpace(txtfname.Text))
{
MessageBox.Show("Please input your firstname!");
}
else if(string.IsNullOrWhiteSpace(txtlname.Text))
{
MessageBox.Show("Please input your lastname!");
}
else if(string.IsNullOrWhiteSpace(cbgender.SelectedItem.ToString()))
{
MessageBox.Show("Please specify your gender!");
}
else if(string.IsNullOrWhiteSpace(txtage.Text) || age <= 0 )
{
MessageBox.Show("Please assign your birthdate to know your age!");
}
else if(string.IsNullOrWhiteSpace(txtcontact.Text))
{
MessageBox.Show("Please input your contact number!");
}
else if(string.IsNullOrWhiteSpace(txtAddress.Text))
{
MessageBox.Show("Please input your address!");
}
else if(string.IsNullOrWhiteSpace(txtUsername.Text))
{
MessageBox.Show("Please input your username!");
}
else if(string.IsNullOrWhiteSpace(txtPass.Text))
{
MessageBox.Show("Please input your password!");
}
else if(string.IsNullOrWhiteSpace(cbxQuest.SelectedItem.ToString()))
{
MessageBox.Show("Please specify your secret question!");
}
else if(string.IsNullOrWhiteSpace(txtAsnwer.Text))
{
MessageBox.Show("Please input your answer!");
}
else
{
//Insert 7
ui.fname = txtfname.Text;
ui.lname = txtlname.Text;
ui.gender = cbgender.SelectedItem.ToString();
ui.age = int.Parse(txtage.Text);
ui.bdate = dtpBdate.Value;
ui.contactNo = txtcontact.Text;
ui.Adress = txtAddress.Text;
//Insert 4
us.username = txtUsername.Text;
us.passwordHash = txtPass.Text;
us.secretQuestion = cbxQuest.SelectedItem.ToString();
us.secretAnswer = txtAsnwer.Text;
StoredProcedure.Insert(ui, us);
dgData.DataSource = StoredProcedure.View();
Clear();
}

String.IsNullOrWhiteSpace has been introduced in .NET 4. If you are not targeting .NET 4 you could easily write your own:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(string value)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
}
which could be used like this:
if (StringExtensions.IsNullOrWhiteSpace(txtfname.Text))
{
// do something
}

Related

Tv Remote Control in C#

I'm new using C# and I'm building a remote control. I got stuck and my code is not compiling. Please I need suggestions and how can I improve my code.
I think its Console.Readline() but I'm not sure how to use it. Also how can change this to 2 primary classes?
public class testRemote
{
public static bool PowerOn(bool powerStatus)
{
if (powerStatus == true)
{
testRemote.DisplayMessage("TV already on");
}
else
{
powerStatus = true;
testRemote.DisplayMessage("TV On, Your Channel is 3 and the Volume is 5");
}
return powerStatus;
}
public static bool PowerOff(bool powerStatus)
{
if (powerStatus == false)
{
testRemote.DisplayMessage("TV already off");
}
else
{
powerStatus = false;
testRemote.DisplayMessage("TV is now off");
}
return powerStatus;
}
public static int VolumeUp(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol >= 10)
{
testRemote.DisplayMessage("TV is already on Maximum Volume.");
}
else
{
vol++;
if (vol == 10)
{
testRemote.DisplayMessage("Maximum Volume.");
}
}
}
return vol;
}
public static int VolumeDown(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol <= 0)
{
testRemote.DisplayMessage("Sound Muted");
}
else
{
vol--;
if (vol == 0)
{
testRemote.DisplayMessage("Sound Muted");
}
}
}
return vol;
}
public static int ChannelUp(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo < 99)
{
channelNo++;
}
else
{
channelNo = 2;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static int ChannelDown(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo == 2)
{
channelNo = 99;
}
else
{
channelNo--;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static String SmartMenu(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Smart Menu On");
md = "TV";
}
return md;
}
public static String SetSettings(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Settings On");
md = "Settings";
}
return md;
}
public static void DisplayMessage(String msg)
{
Console.WriteLine(msg);
}
public static void Banner()
{
Console.WriteLine("Welcome to TV Remote Control");
Console.WriteLine("Please enter your selection");
Console.WriteLine("Power On - turns on your TV");
Console.WriteLine("Power Off - turns off your TV");
Console.WriteLine("Increase volume - turns up the volume");
Console.WriteLine("Decrease volume - turn down the volume");
Console.WriteLine("Channel Up - increments the channel");
Console.WriteLine("Channel Down - decrements the channel");
Console.WriteLine("Smart Menu");
Console.WriteLine("Settings");
Console.WriteLine();
Console.WriteLine("Please enter your selection");
}
public static void Main(String[] args)
{
bool powerOn = false;
int channel = 3;
int volume = 5;
string mode = "TV";
string choice = "Turn On";
string c = Console.ReadLine();
while (choice.ToLower().Equals("Exit".ToLower()) != true)
{
if (choice.ToLower().Equals("Power On".ToLower()) == true)
{
powerOn = testRemote.PowerOn(powerOn);
}
if (choice.ToLower().Equals("Power Off".ToLower()) == true)
{
powerOn = testRemote.PowerOff(powerOn);
}
if (choice.ToLower().Equals("Increase volume".ToLower()) == true)
{
volume = testRemote.VolumeUp(powerOn, volume);
}
if (choice.ToLower().Equals("Decrease volume".ToLower()) == true)
{
volume = testRemote.VolumeDown(powerOn, volume);
}
if (choice.ToLower().Equals("Channel Up".ToLower()) == true)
{
channel = testRemote.ChannelUp(powerOn, channel);
}
if (choice.ToLower().Equals("Channel Down".ToLower()) == true)
{
channel = testRemote.ChannelDown(powerOn, channel);
}
if (choice.ToLower().Equals("Mode TV".ToLower()) == true)
{
mode = testRemote.SmartMenu(powerOn, mode);
}
if (choice.ToLower().Equals("Mode DVD".ToLower()) == true)
{
mode = testRemote.SetSettings(powerOn, mode);
}
Console.WriteLine();
Console.WriteLine();
choice = Console.ReadLine();
}
Console.WriteLine("Thank you for the Remote Controller");
Console.ReadLine();
}
}
Since the question is not clear i slightly modified your code, it compiles and runs BUT needs a lot of refactor.
Here is the working code.
using System;
namespace TvRemote
{
public class testRemote
{
public static bool PowerOn(bool powerStatus)
{
if (powerStatus == true)
{
testRemote.DisplayMessage("TV already on");
}
else
{
powerStatus = true;
testRemote.DisplayMessage("TV On, Your Channel is 3 and the Volume is 5");
}
return powerStatus;
}
public static bool PowerOff(bool powerStatus)
{
if (powerStatus == false)
{
testRemote.DisplayMessage("TV already off");
}
else
{
powerStatus = false;
testRemote.DisplayMessage("TV is now off");
}
return powerStatus;
}
public static int VolumeUp(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol >= 10)
{
testRemote.DisplayMessage("TV is already on Maximum Volume.");
}
else
{
vol++;
if (vol == 10)
{
testRemote.DisplayMessage("Maximum Volume.");
}
}
}
return vol;
}
public static int VolumeDown(bool powerStat, int vol)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (vol <= 0)
{
testRemote.DisplayMessage("Sound Muted");
}
else
{
vol--;
if (vol == 0)
{
testRemote.DisplayMessage("Sound Muted");
}
}
}
return vol;
}
public static int ChannelUp(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo < 99)
{
channelNo++;
}
else
{
channelNo = 2;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static int ChannelDown(bool powerStat, int channelNo)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
if (channelNo == 2)
{
channelNo = 99;
}
else
{
channelNo--;
}
Console.WriteLine("Channel " + channelNo.ToString());
}
return channelNo;
}
public static String SmartMenu(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Smart Menu On");
md = "TV";
}
return md;
}
public static String SetSettings(bool powerStat, String md)
{
if (powerStat == false)
{
testRemote.DisplayMessage("TV is off");
}
else
{
testRemote.DisplayMessage("Settings On");
md = "Settings";
}
return md;
}
public static void DisplayMessage(String msg)
{
Console.WriteLine(msg);
}
public static void Banner()
{
Console.WriteLine("Welcome to TV Remote Control");
Console.WriteLine("Please enter your selection");
Console.WriteLine("Power On - turns on your TV");
Console.WriteLine("Power Off - turns off your TV");
Console.WriteLine("Increase volume - turns up the volume");
Console.WriteLine("Decrease volume - turn down the volume");
Console.WriteLine("Channel Up - increments the channel");
Console.WriteLine("Channel Down - decrements the channel");
Console.WriteLine("Smart Menu");
Console.WriteLine("Settings");
Console.WriteLine();
Console.WriteLine("Please enter your selection");
}
public static void Main(String[] args)
{
bool powerOn = false;
int channel = 3;
int volume = 5;
string mode = "TV";
//string choice = "Turn On"; //THIS MUST BE Power On if you want to power on the tv as soon as the app is launched
Banner();
string choice = Console.ReadLine();
while (!choice.ToLower().Equals("Exit".ToLower()))
{
if (choice.ToLower().Equals("Power On".ToLower()) == true)
{
powerOn = testRemote.PowerOn(powerOn);
}
if (choice.ToLower().Equals("Power Off".ToLower()) == true)
{
powerOn = testRemote.PowerOff(powerOn);
}
if (choice.ToLower().Equals("Increase volume".ToLower()) == true)
{
volume = testRemote.VolumeUp(powerOn, volume);
}
if (choice.ToLower().Equals("Decrease volume".ToLower()) == true)
{
volume = testRemote.VolumeDown(powerOn, volume);
}
if (choice.ToLower().Equals("Channel Up".ToLower()) == true)
{
channel = testRemote.ChannelUp(powerOn, channel);
}
if (choice.ToLower().Equals("Channel Down".ToLower()) == true)
{
channel = testRemote.ChannelDown(powerOn, channel);
}
if (choice.ToLower().Equals("Mode TV".ToLower()) == true)
{
mode = testRemote.SmartMenu(powerOn, mode);
}
if (choice.ToLower().Equals("Mode DVD".ToLower()) == true)
{
mode = testRemote.SetSettings(powerOn, mode);
}
Console.WriteLine();
Console.WriteLine();
choice = Console.ReadLine();
}
Console.WriteLine("Thank you for the Remote Controller");
Console.ReadLine();
}
}
}

Unity console not showing Debug upon pressing play

I am creating a small login page example and upon pressing play I am not getting any of the Debug messages I am expected if the email/password/confirm password is not according to the conditions set.
Here is the whole code:
Packages
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System;
using System.Text.RegularExpressions;
Class definition
public class Register : MonoBehaviour
{
public GameObject username;
public GameObject email;
public GameObject password;
public GameObject confPassword;
private string Username;
private string Email;
private string Password;
private string ConfPassword;
private string form;
private bool EmailValid = false;
private string[] Characters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","O","N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","_","-" };
Initiation and setting conditions for username, email, password and confirm password.
// Start is called before the first frame update
void Start()
{
}
public void RegisterButton()
{
print("Registration Successful");
bool UN = false;
bool EM = false;
bool PW = false;
bool CPW = false;
if (Username != "")
{
if (!System.IO.File.Exists(#"E:/UnityTestFolder/" + Username + ".txt"))
{
UN = true;
}
else
{
Debug.LogWarning("Username Taken");
}
}
else
{
Debug.LogWarning("Username field empty");
}
if (Email != "")
{
EmailValidation();
if (EmailValid)
{
if (Email.Contains("#"))
{
if (Email.Contains("."))
{
EM = true;
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email field empty ");
}
if (Password != "")
{
if (Password.Length > 5)
{
PW = true;
}
else
{
Debug.LogWarning("Pass must be at least 6 characters long!");
}
}
else
{
Debug.LogWarning("Password field empty");
}
if (ConfPassword != "")
{
if (ConfPassword == Password)
{
CPW = true;
}
else
{
Debug.LogWarning("Passwords do not match!");
}
}
else
{
Debug.LogWarning("Confirm password field empty");
}
if (UN == true &&EM == true &&PW == true &&CPW == true)
{
bool Clear = true;
int i = 1;
foreach (char c in Password)
{
if (Clear)
{
Password = "";
Clear = false;
}
i++;
char Encrypted = (char)(c * i);
Password += Encrypted.ToString();
}
form = (Username + "\n" + Email + "\n" + Password);
System.IO.File.WriteAllText(#"E:/ UnityTestFolder / " + Username + ".txt", form);
username.GetComponent<InputField>().text = "";
email.GetComponent<InputField>().text = "";
password.GetComponent<InputField>().text = "";
confPassword.GetComponent<InputField>().text = "";
print("Registration complete");
}
}
Calling update - pressing tab button to navigate between the various placeholders.
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
if (username.GetComponent<InputField>().isFocused)
{
email.GetComponent<InputField>().Select();
}
if (email.GetComponent<InputField>().isFocused)
{
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused)
{
confPassword.GetComponent<InputField>().Select();
}
}
if (Input.GetKeyDown(KeyCode.Return))
{
if (Password != ""&&Email != ""&&Password != ""&&ConfPassword != "")
{
RegisterButton();
}
}
Username = username.GetComponent<InputField>().text;
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confPassword.GetComponent<InputField>().text;
}
void EmailValidation()
{
bool SW = false;
bool EW = false;
for (int i = 0; i < Characters.Length; i++)
{
if (Email.StartsWith(Characters[i]))
{
SW = true;
}
}
for (int i = 0; i < Characters.Length; i++)
{
if (Email.EndsWith(Characters[i]))
{
EW = true;
}
}
if (SW = true &&EW == true)
{
EmailValid = true;
}
else
{
EmailValid = false;
}
}
}
Thanks for the help.
Add [ExecuteInEditMode] attribute here:
[ExecuteInEditMode]
public class Register : MonoBehaviour
I have resolved it, it was a stupid mistake, I just had the wrong GameObject in the "On Click" component.
Thanks for all help again.

c# how to make my program run through multiple times without setting the amount

Here is my code:
class Main
{
public string Name()
{
string employee = "";
while (employee == "")
{
try
{
Console.Write("Please enter employee name: ");
employee = Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
return employee;
}
public float hoursWorked()
{
string yesno = "";
List<float> hWorked = new List<float>();
float hours = 0;
for (int i = 0; yesno == "" || yesno =="Yes"|| yesno== "yes"; i++)
{
try
{
Console.Write("Please enter hours worked: ");
hours = float.Parse(Console.ReadLine());
if (hours > 0)
{
Console.WriteLine("Hours added");
hWorked.Add(hours);
}
else
{
Console.WriteLine("Please enter valid hours");
}
Console.Write("Do you want to add more hours? Please state Yes or No: ");
yesno = Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
return hWorked.Sum();
}
}
class Program
{
static void Main(string[] args)
{
Main a = new Main();
string name = a.Name();
float hWorked = a.hoursWorked();
string more = "";
Console.WriteLine("Name: {0}\nHours worked: {1}", name, hWorked);
Console.Write("Add another employee?: ");
more = Console.ReadLine();
if (more == "Yes" || more == "yes")
{
Main b = new Main();
string name1 = a.Name();
float hWorked1 = a.hoursWorked()
Console.WriteLine("Name: {0}\nHours worked: {1}", name, hWorked1);
Console.ReadLine();
}
else
{
Console.ReadLine();
}
}
}
What i want to do is allow the user to answer Yes or No to the question "Add another employee?:" I can do this by just using the if statement you see at the bottom. How am i able to allow this without presetting the number of times they can add another employee?
The code is very rustic. I changed your hoursWorked method just a little do get what you need:
public float hoursWorked()
{
string yesno = "";
List<float> hWorked = new List<float>();
float hours = 0;
do
{
try
{
Console.Write("Please enter hours worked: ");
hours = float.Parse(Console.ReadLine());
if (hours > 0)
{
Console.WriteLine("Hours added");
hWorked.Add(hours);
}
else
{
Console.WriteLine("Please enter valid hours");
}
Console.Write("Do you want to add more hours? Please state Yes or No: ");
yesno = Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
} while (yesno != null && yesno.ToUpper() != "NO");
return hWorked.Sum();
}
I did not change anything else. You can drastically improve this logic.
You could try using do
do
{
input data
} while(some condition to continue)
MSDN documentation
I think part of the problem is that you're mixing the program flow with the work you're trying to do. I have done a quick version which shows the program flow being controlled by Main while using an Employee class to encapsulate the name and list of hours worked.
Note that I have also simplified the input by looking for an empty string to determine when they want to stop entering data, but that could easily be changed to use your yes/no responses if required.
static void Main(string[] args)
{
// Add new employees
while(true)
{
Console.WriteLine("Please enter employee name: ");
var employeeName = Console.ReadLine();
if (string.IsNullOrWhiteSpace(employeeName))
break;
var employee = new Employee(employeeName);
// Add employee hours
while(true)
{
Console.WriteLine("Please enter hours worked: ");
var inputHours = Console.ReadLine();
if (string.IsNullOrWhiteSpace(inputHours))
{
Console.WriteLine("Name: {0}\nHours worked: {1}", employee.Name, employee.HoursWorked.Sum());
break;
}
var hours = float.Parse(inputHours);
if (hours > 0)
{
employee.HoursWorked.Add(hours);
Console.WriteLine("Hours added");
}
else
{
Console.WriteLine("Please enter valid hours");
}
}
}
}
public class Employee
{
private readonly string _name;
public Employee(string name)
{
_name = name;
HoursWorked = new List<float>();
}
public string Name
{
get { return this._name; }
}
public List<float> HoursWorked { get; set; }
}

ListBox doesnt show any results

I'm trying to add an array of strings that holds information about people to a ListBox but i cant get it to show anything and i really dont know why.
This is the first class that is called when the button to add contacts to the list is clicked.
public partial class MainForm : Form
{
private ContactManager m_contacts;
public MainForm()
{
InitializeComponent();
m_contacts = new ContactManager();
InitializeGUI();
}
private void InitializeGUI()
{
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtStreet.Text = string.Empty;
txtCity.Text = string.Empty;
txtZipCode.Text = string.Empty;
cmbCountry.Items.AddRange(Enum.GetNames(typeof(Countries)));
cmbCountry.DropDownStyle = ComboBoxStyle.DropDownList;
cmbCountry.SelectedIndex = (int)Countries.Sverige;
UpdateGUI();
}
private bool ReadInput(out Contact contact)
{
// skapar ett lokalt objekt av Contact-klassen
contact = new Contact();
// Lägger in ReadAdress till ett objekt i klassen Adress.
Address adr = ReadAddress();
contact.AddressData = adr; // skickar adress till contact-objekt
//bool readNameOK = ReadName();
// ReadName är OK så skickas det till AddContact.
if (ReadName())
{
m_contacts.AddContact(contact);
}
return ReadName();
} // ReadInput
private bool ReadName()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
bool firstname = false;
bool lastname = false;
if (!InputUtility.ValidateString(contact.FirstName))
{
MessageBox.Show("You must enter a first name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
firstname = false;
}
else if (!InputUtility.ValidateString(contact.LastName))
{
MessageBox.Show("You must enter a last name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
lastname = false;
}
return firstname && lastname;
}
private Address ReadAddress()
{
Address address = new Address();
address.Street = txtStreet.Text;
address.City = txtCity.Text;
address.ZipCode = txtZipCode.Text;
address.Country = (Countries)cmbCountry.SelectedIndex;
return address;
}
private void button1_Click(object sender, EventArgs e)
{
Contact contact;
if (ReadInput(out contact))
{
UpdateGUI();
}
}
private void UpdateGUI()
{
lstContacts.Items.Clear();
lstContacts.Items.AddRange(m_contacts.GetContactsInfo());
lblCount.Text = m_contacts.Count().ToString();
}
private void lstContacts_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateContactInfoFromRegistry();
}
private void UpdateContactInfoFromRegistry()
{
Contact contact = m_contacts.GetContact(lstContacts.SelectedIndex);
cmbCountry.SelectedIndex = (int)contact.AddressData.Country;
txtFirstName.Text = contact.FirstName;
txtLastName.Text = contact.LastName;
txtCity.Text = contact.AddressData.City;
txtStreet.Text = contact.AddressData.Street;
txtZipCode.Text = contact.AddressData.ZipCode;
}
}
This class then calls this class
public class ContactManager
{
private List<Contact> m_contactRegistry;
public ContactManager()
{
m_contactRegistry = new List<Contact>();
}
public int Count()
{
int count = m_contactRegistry.Count();
return count;
}
public bool CheckIndex(int index)
{
if (index >= 0 && index < m_contactRegistry.Count())
return true;
else return false;
}
public bool AddContact(string firstName, string lastName, Address addressIn)
{
Contact contactObj = new Contact();
bool result = false;
if (!result)
{
contactObj.FirstName = firstName;
contactObj.LastName = lastName;
contactObj.AddressData = addressIn;
m_contactRegistry.Add(contactObj);
result = true;
}
return result;
}
public bool AddContact(Contact contactIn)
{
if (contactIn == null)
{
return false;
}
else
{
m_contactRegistry.Add(contactIn);
return true;
}
}
public bool changeContact(Contact contactIn, int index)
{
if (CheckIndex(index))
{
Contact contact = (Contact)m_contactRegistry[index];
//contact.ToString = contactIn;
return true;
}
else return false;
}
public bool DeleteContact(int index)
{
if (CheckIndex(index))
{
m_contactRegistry.RemoveAt(index);
return true;
}
else return false;
}
public Contact GetContact(int index)
{
if (!CheckIndex(index))
return null;
else return m_contactRegistry[index];
}
public string[] GetContactsInfo()
{
string[] strInfoStrings = new string[m_contactRegistry.Count];
int i = 0;
foreach (Contact contactObj in m_contactRegistry)
{
strInfoStrings[i++] = contactObj.ToString();
}
return strInfoStrings;
}
}
Any help regarding why the arrays wont show up in the listbox would be much appriciated, thanks.
Your ReadName() always returns false, there for it never adds the contacts.
EDIT:
A clearer code
private Contact ReadInput()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
contact.AddressData = new Address
{
Street = txtStreet.Text,
City = txtCity.Text,
ZipCode = txtZipCode.Text,
Country = (Countries) cmbCountry.SelectedIndex
};
return contact;
}
private bool ValidateContact(Contact contact)
{
if ( !InputUtility.ValidateString( contact.FirstName ) )
{
MessageBox.Show( "You must enter a first name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
return false;
}
else if ( !InputUtility.ValidateString( contact.LastName ) )
{
MessageBox.Show( "You must enter a last name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
return false;
}
return true;
}
private void button1_Click( object sender, EventArgs e )
{
Contact contact = ReadInput();
if ( ValidateContact( contact ) )
{
m_contacts.AddContact(contact);
UpdateGUI();
}
}

My message wont show on my textbox?

I am trying to fill a form (Movie information such as Title, Year and Genre) and then show it in a textbox (enable=false).
I have 2 classes and a Form (with 2 textboxes (for user input), 2 buttons, 1 to register the movie infos, and 1 to show the infos in a 3rd textbox (the one that is Disabled).
class Movies
{
public string Title { get; set; }
public int Year { get; set; }
public string ReturnMovie()
{
return Title + " (" + Year.ToString() + ")";
}
}
class Genres
{
public string Genre { get; set; }
public string ReturnGenre()
{
return Genre;
}
}
MainForm:
bool btnRegisterClicked = false;
Movies m1 = new Movies();
Genres g1 = new Genres();
private void btnRegister_Click(object sender, EventArgs e)
{
btnRegisterClicked = true;
if (btnRegisterClicked == true)
{
if (txtTitle.Text.Length == 0)
{
MessageBox.Show("Enter a title for the movie.");
btnRegisterClicked = false;
}
else if (txtYear.Text.Length < 4)
{
MessageBox.Show("Enter a valid year.");
btnRegisterClicked = false;
}
else if (chkGenre.SelectedIndex == -1)
{
MessageBox.Show("Select the genre(s) of the movie.");
btnRegisterClicked = false;
}
else
{
txtTitle.Text = m1.Title;
txtYear.Text = m1.Year.ToString();
chkGenre.Text = g1.Genre;
}
txtTitle.Clear();
txtYear.Clear();
chkGenre.ClearSelected();
}
}
private void btnShow_Click(object sender, EventArgs e)
{
txtShow.Text = m1.ReturnMovie() + g1.ReturnGenre();
}
}
What am I doing wrong ?
The assignments in your else block are backwards. You're setting the TextBox to the un-initalized contents of m1 and g1, and then immediately .Clear()ing them out.
else
{
m1.Title = txtTitle.Text;
m1.Year = int.Parse(txtYear.Text);
g1.Genre = chkGenre.Text
}
You need to assign values to variables not to controls..., change following
else
{
txtTitle.Text = m1.Title;
txtYear.Text = m1.Year.ToString();
chkGenre.Text = g1.Genre;
}
to
else
{
m1.Title = txtTitle.Text;
m1.Year = int.Parse(txtYear.Text);
g1.Genre = chkGenre.Text;
}

Categories