I'm doing a program for a class, and when I run it and type something in the txtSSN control that's not valid, it freezes up and crashes. I can't figure it out because I have another very similar project that works just fine.
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.Text.RegularExpressions;
namespace VitalStatistics
{
public partial class frmVitalStatistics : Form
{
#region Declarations
const String AppTitle = "Vital Statistics";
const float hoursOffset = 24.999F;
Regex ssnRegex;
#endregion
#region Constructors
public frmVitalStatistics()
{
InitializeComponent();
}
#endregion
#region Event Handlers
private void frmVitalStatistics_Load(object sender, EventArgs e)
{
// Initialize SSN input control
RegexOptions options = RegexOptions.IgnorePatternWhitespace;
string pattern = #"\A\d{3}-\d{3}-\d{4}\Z";
ssnRegex = new Regex(pattern, options);
// Init. Gender controls
optGender = Gender.Unassigned;
rbFemale.Tag = Gender.Male;
rbMale.Tag = Gender.Female;
// Init dtpBirth controls
dtpBirth.MinDate = DateTime.Today;
dtpBirth.MaxDate = DateTime.Today.AddHours(hoursOffset);
dtpBirth.Value = DateTime.Today;
}
private void btnSubmit_Click(object sender, EventArgs e)
{
string name = String.Empty;
string ssn = String.Empty;
int length = 0;
int weight = 0;
DateTime birthDate = DateTime.MinValue;
Gender gender = Gender.Unassigned;
//Gather inputs
if (GetName(ref name) &&
GetSSN(ref ssn) &&
GetLength(ref length) &&
GetWeight(ref weight) &&
GetGender(ref gender) &&
GetBirthDate(ref birthDate))
{
//submit & close
string format =
"Thank you for submitting your contact information. \n\n" +
"Name: {0}\n" +
"SSN: {1}\n" +
"Length: {2}\n" +
"Weight: {3}\n" +
"Gender: {4}\n" +
"Birth Date & Time: {5:D}\n";
string msg = String.Format(format, name, ssn, length, weight, gender, birthDate);
MessageBox.Show(msg,AppTitle);
Close();
}
}
private Gender optGender;
private void Gender_CheckedChanged(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
optGender = (rb.Checked ? (Gender)rb.Tag : Gender.Unassigned);
}
#endregion
#region Implementation
bool GetName(ref string name)
{
if (String.IsNullOrWhiteSpace(txtName.Text))
{
txtName.SelectAll();
txtName.Focus();
ShowError("Please enter your name.\n Names cannot consist of whitespace.");
return false;
}
name = txtName.Text.Trim();
return true;
}
bool GetSSN(ref string ssn)
{
txtSSN.Text = txtSSN.Text.Trim();
Match match = ssnRegex.Match(txtSSN.Text);
if (!match.Success)
{
txtSSN.SelectAll();
txtSSN.Focus();
ShowError("Unrecognized format for SSN. Please enter in the following format: 000-000-0000.");
return false;
}
ssn = txtSSN.Text;
return true;
}
bool GetLength(ref int length)
{
int value;
try
{
if (String.IsNullOrWhiteSpace(txtLength.Text))
throw new ArgumentException("Field cannot be empty or contain spaces.");
value = int.Parse(txtLength.Text);
}
catch (Exception ex)
{
// Select text and set focus
txtLength.SelectAll();
txtLength.Focus();
// Set up error Message
string msg = String.Format("{0}", ex);
ShowError(ex.Message);
return false;
}
length = value;
return true;
}
bool GetWeight(ref int weight)
{
int value;
try
{
if (String.IsNullOrWhiteSpace(txtWeight.Text))
throw new ArgumentException("Field cannot be empty or contain spaces.");
value = int.Parse(txtLength.Text);
}
catch (Exception ex)
{
// Select text and set focus
txtWeight.SelectAll();
txtWeight.Focus();
// Set up error Message
string msg = String.Format("{0}", ex);
ShowError(ex.Message);
return false;
}
weight = value;
return true;
}
bool GetGender(ref Gender gender)
{
if (optGender == Gender.Unassigned)
{
ShowError("Select a Gender.");
return false;
}
gender = optGender;
return true;
}
bool GetBirthDate(ref DateTime birthDate)
{
birthDate = dtpBirth.Value;
return true;
}
void ShowError(string msg)
{
MessageBox.Show(msg, AppTitle, MessageBoxButtons.OK, MessageBoxIcon.None);
}
#endregion
}
}
Judging by the comments and the code it sounds as if you don't have the event handler frmVitalStatistics_Load connected to the load event of the form. This would cause a null pointer exception which would be consistent the error you are seeing.
As per my comments to the OP, if frmVitalStatistics_Load isn't running, it may not be hooked up right as an event handler.
I have been unable to reproduce the error you are seeing with the code you posted. There is likely something in your frmVitalStatistics.Designer.cs file that is different than what I came up with.
As others have said, it could be an event that is missing or perhaps an extra event hooked up that isn't needed.
These are the only events I have hooked up in the form.
this.rbMale.CheckedChanged += new System.EventHandler(this.Gender_CheckedChanged);
this.rbFemale.CheckedChanged += new System.EventHandler(this.Gender_CheckedChanged);
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
this.Load += new System.EventHandler(this.frmVitalStatistics_Load);
Check your frmVitalStatistics.Designer.cs and see if you have any others or if any of these are missing.
One question... Is it freezing AS you are typing or after you click Submit?
Related
I am currently making a fitness class booking system for some study I am doing so please bare with me.
I have done most of the code but I am having this strange issue with my 2nd radio button for selecting what class you want.
I have set up my code so a message box appears if the Member ID you have entered is already registered to the fitness class you have selected. For my RadioButton1 (rbCardioClass) and RadioButton2 (rbPilatesClass), the error message box works great and works as it should. But my RadioButton2 (rbSpinClass) will make the error message box appear everytime, even if the MemberID is not associated to the 'Spin Class'.
I have tried different uses of if statements, different radio buttons etc but can't seem to get it to work the way I want.
If I go to my servicesErrorCheck(string[] description)method and just the temp variable to true all radio buttons save to the database table correctly BUT I then lose my erroring, which makes me thinks it is something to do with the way I have set up the message box, maybe.
Here is a screenshot of the prototype form just for reference. FitnessClassBooking Form
Here is a screenshot of the table while the app is running App Running Fitness Form
Here is the error being thrown with MemberID that has no 'Spin' class associated with it App Running Error
Here is my code in question -
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.Data.SqlClient;
using System.Configuration;
namespace Membership_Formv2
{
public partial class FitnessClassBooking : Form
{
public FitnessClassBooking()
{
InitializeComponent();
}
private void bMainMenu_Click(object sender, EventArgs e)
{
new MainMenu().Show();
this.Hide();
}
private void fitnessInformationBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.fitnessInformationBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.databaseDataSet);
}
private void FitnessClassBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'databaseDataSet.Members' table. You can move, or remove it, as needed.
this.membersTableAdapter.Fill(this.databaseDataSet.Members);
// TODO: This line of code loads data into the 'databaseDataSet.FitnessInformation' table. You can move, or remove it, as needed.
this.fitnessInformationTableAdapter.Fill(this.databaseDataSet.FitnessInformation);
}
private void fitnessInformationDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string descriptionfit()
{
string className = "";
if (rbCardioClass.Checked == true)
{
className = "Cardio";
}
else if (rbSpinClass.Checked == true)
{
className = "Spin";
}
else if (rbPilatesClass.Checked == true)
{
className = "Pilates";
}
return className;
}
private string classDescription()
{
string serviceSeletionString = "Class";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
return serviceSeletionString;
}
private bool errorCheckingID()
{
bool statusDB = true;
//Getting row info from MembersTa table
DatabaseDataSet.MembersRow newEntry = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox3.Text));
//Getting information from BookingTa table
if (newEntry == null)
{
statusDB = false;
return (statusDB);
}
return (statusDB);
}
public bool servicesErrorCheck(string[] description)
{
bool temp = true;
string serviceSeletionString = "";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
for (int t = 0; t < description.Length; t++)
{
if (serviceSeletionString.Contains(description[t].Trim()))
{
temp = false;
break;
}
}
return (temp);
}
private string originalaccesdb()
{
string a = "";
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = descriptionfit();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
return a;
}
private string[] accessDB()
{
int t = 0;
int temp;
string[] servicesList = { "n", "n", "n" }; //This variable will store the data
//Same code too extract table information
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox3.Text))
{
//Store inside the array all the services/description against the ID.
//Note that this array will remain "" for all the elements inside the array
//if no descritopn/services (i.e., record) is found against the input ID
servicesList[t] = r["Description"].ToString();
t = t + 1;
}
}
return (servicesList);
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
textBox1.Text = "";
int a = Int32.Parse(textBox2.Text);
DatabaseDataSet.MembersRow newID = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox2.Text));
string booking = "";
int temp;
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox2.Text))
{
booking = r["Description"].ToString() + ", " + booking;
}
}
textBox1.Text = "Member ID is: " + (newID.MemberID).ToString() + Environment.NewLine +
"First Name is: " + (newID.First_Name).ToString() + Environment.NewLine +
"Last Name is: " + (newID.Last_Name).ToString() + Environment.NewLine +
"Bookings: " + booking;
}
public void button2_Click(object sender, EventArgs e)
{
bool status1, status2;
string[] description;
//Error control at the outer level for valid ID
status1 = errorCheckingID();
//Proceed only if ID is valid or status1 is true
if (status1)
{
//Retrieve information from the other database. Ideally you want this method to return
//an array containing registered services. This would be an array of strings.
description = accessDB();
//Services error checking
status2 = servicesErrorCheck(description);
//Now this is the code that would call the method to save data ito database
//when status2 and 2 are true
if (status2)
{
//Code for saving into database.
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = classDescription();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
}
else
{
//Show error that this service is not available
MessageBox.Show("This Class is already assigned to that Member ID");
}
}
else
{
//Error message invalid ID
MessageBox.Show("Invalid ID");
}
}
private void radioButton1_Click(object sender, EventArgs e)
{
}
private void radioButton4_Click(object sender, EventArgs e)
{
}
private void radioButton3_Click(object sender, EventArgs e)
{
}
}
}
I am really not sure why this is happening so I would really appreciate any help.
You are checking each string in descriptions as follows:
serviceSeletionString.Contains(description[t].Trim())
which considering at least one of the strings is just n it will always match Spin.
Quite why you are always returning an array with the blank ones having n, I don't know. Personally I would just use a List<string> and Add each item from the database to it. But that is a separate point.
Either change it to serviceSeletionString == description[t] (don't see why you need Trim()) or just replace the whole foreach loop with description.Contains(serviceSeletionString)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.
I'm trying to debug this code, but in third method it's not allowing me to use different data types. In my textbook, the example shows them using different data types as an argument. Why isn't it allowing me to do so? I'm sure that this code has other issues, but I can't even debug them until I clear the errors.
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 WP_Week3_Problem2
{
public partial class Problem2 : Form
{
public Problem2()
{
InitializeComponent();
}
int[] productID = { 1234, 5678, 5677, 8765, 2345, 8734 };
double[] productPrice = { 5.55, 20.0, 40.0, 56.34, 78.10, 98.0 };
String[] productName = { "Pencil", "Backpack", "MessengerBag", "RoomHeater", "SewingMachine", "Decorative Lamp" };
private void Problem2_Load(object sender, EventArgs e)
{
}
private void buttonLoadTable_Click(object sender, EventArgs e)
{
labelOutput.Text = "ProdID Price ProdName";
for (int i = 0; i < productID.Length; i = i + 1)
{
labelOutput.Text += String.Format("\n {0} {1} {2} ", productID[i], productPrice[i].ToString("C"), productName[i]);
}
}
private void buttonSearch_Click(object sender, EventArgs e)
{
int prodID = Convert.ToInt32(textBoxID.Text);
String prodName = textBoxName.Text;
double prodPrice = Convert.ToDouble(textBoxPrice.Text);
SearchProducts(prodID);
SearchProducts(prodName);
SearchProducts(prodID, prodName, prodPrice);
}
private void SearchProducts(int prodID)
{
int prodMinus = prodID - 1;
int idExists = Array.IndexOf(productID, prodMinus);
if (idExists == -1)
{
labelOutput.Text = "That product ID is invalid.\nPlease enter a valid product ID";
textBoxID.Text = "";
}
}
private void SearchProducts(String prodName)
{
String nameExists = Array.IndexOf(productName, prodName).ToString();
bool isName = true;
if (nameExists == "Pencil")
isName = true;
else if (nameExists == "Backpack")
isName = true;
else if (nameExists == "MessengerBag")
isName = true;
else if (nameExists == "RoomHeater")
isName = true;
else if (nameExists == "SewingMachine")
isName = true;
else if (nameExists == "Decorative Lamp")
isName = true;
else
isName = false;
labelOutput.Text = "This Product Name is invalid.\nPlease enter a valid Product Name";
}
private void SearchProducts(String prodName, int prodID, double prodPrice)
{
labelOutput.Text = String.Format("Your Product ID of {0} is a {2} and it costs: {1}", prodID, prodName, prodPrice.ToString("C"));
}
}
}
You could also usefully do with some error handling on the text box conversions - it is never a good plan to take a text box and expect the user to simply enter valid data:
private void buttonSearch_Click(object sender, EventArgs e)
{
bool process = true;
String prodName = textBoxName.Text;
int prodID;
double prodPrice;
try
{
prodID = Convert.ToInt32(textBoxID.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error in product ID", MessageBoxButtons.OK, MessageBoxIcon.Error);
process = false;
}
try
{
prodPrice = Convert.ToDouble(textBoxPrice.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in product price", MessageBoxButtons.OK, MessageBoxIcon.Error);
process = false;
}
if (process)
{
SearchProducts(prodID);
SearchProducts(prodName);
SearchProducts(prodID, prodName, prodPrice);
}
}
Edit:
I did forget to say that you could replace Convert with the class parsers, this avoids the need for a try/catch:
if (!Int32.TryParse(textBoxID.Text, out prodID))
{
process = false;
// message method of choice to tell user of error
}
Change this line
SearchProducts(prodID, prodName, prodPrice);
to this one
SearchProducts(prodName, prodID, prodPrice);
The SearchProducts method expects String, int and double parameters, but you passed an int, string and double.
This is how i List and Add all the win32 items to the ComboBox.
using System;
using System.Collections;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GetHardwareInfo
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
cmbxOption.SelectedItem = "Win32_Processor";
cmbxStorage.SelectedItem = "Win32_DiskDrive";
cmbxMemory.SelectedItem = "Win32_CacheMemory";
cmbxSystemInfo.SelectedItem = "";
cmbxNetwork.SelectedItem = "Win32_NetworkAdapter";
cmbxUserAccount.SelectedItem = "Win32_SystemUsers";
cmbxDeveloper.SelectedItem = "Win32_COMApplication";
cmbxUtility.SelectedItem = "Win32_1394Controller";
}
private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
{
lst.Items.Clear();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from " + Key);
try
{
foreach (ManagementObject share in searcher.Get())
{
ListViewGroup grp;
try
{
grp = lst.Groups.Add(share["Name"].ToString(), share["Name"].ToString());
}
catch
{
grp = lst.Groups.Add(share.ToString(), share.ToString());
}
if (share.Properties.Count <= 0)
{
MessageBox.Show("No Information Available", "No Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
foreach (PropertyData PC in share.Properties)
{
ListViewItem item = new ListViewItem(grp);
if (lst.Items.Count % 2 != 0)
item.BackColor = Color.White;
else
item.BackColor = Color.WhiteSmoke;
item.Text = PC.Name;
if (PC.Value != null && PC.Value.ToString() != "")
{
switch (PC.Value.GetType().ToString())
{
case "System.String[]":
string[] str = (string[])PC.Value;
string str2 = "";
foreach (string st in str)
str2 += st + " ";
item.SubItems.Add(str2);
break;
case "System.UInt16[]":
ushort[] shortData = (ushort[])PC.Value;
string tstr2 = "";
foreach (ushort st in shortData)
tstr2 += st.ToString() + " ";
item.SubItems.Add(tstr2);
break;
default:
item.SubItems.Add(PC.Value.ToString());
break;
}
}
else
{
if (!DontInsertNull)
item.SubItems.Add("No Information available");
else
continue;
}
lst.Items.Add(item);
}
}
}
catch (Exception exp)
{
MessageBox.Show("can't get data because of the followeing error \n" + exp.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void RemoveNullValue(ref ListView lst)
{
foreach (ListViewItem item in lst.Items)
if (item.SubItems[1].Text == "No Information available")
item.Remove();
}
#region Control events ...
private void cmbxNetwork_SelectedIndexChanged(object sender, EventArgs e)
{
InsertInfo(cmbxNetwork.SelectedItem.ToString(), ref lstNetwork, chkNetwork.Checked);
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
linkLabel1.LinkVisited = true;
}
#endregion
}
}
What i get is in the end that in the ComboBox in this case i call it cmbxNetwork i see in it many items all start with Win32_
For example when i click on ComboBox i see the first item is: "Win32_NetworkAdapter"
Instead Win32_NetworkAdapter i want to see in the ComboBox only: NetworkAdapter
But when i select the item it should be selected as Win32_NetworkAdapter but the user should see and select only NetworkAdapter.
I want to remove as test from the ComboBox items the Win32_
But only that the user will see it without Win32_
Also in the constructor when i'm doing now: cmbxNetwork.SelectedItem = "Win32_NetworkAdapter"; so instead if i'm doing: cmbxNetwork.SelectedItem = "NetworkAdapter"; it will be enough. THe program will use the "Win32_NetworkAdapter"; but again what i see and user in the ComboBox as item is only the NetworkAdapter
You might use objects from a self-written structure which encapsulates a value and a display string:
class Box {
public object Value { get; set; }
public string Display { get; set; }
public override string ToString() { return Display; }
}
Put your values into a Box-class and define a display-string. The ComboBox will show the result of ToString.
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 Cameron_PickerillTrinitapoli_Assn1
{
public partial class seasonalBttnChanger : Form
{
public seasonalBttnChanger()
{
InitializeComponent();
}
//Triggers when program first loads
//Sets up
private void bttnChanger_Load(object sender, EventArgs e)
{
List<Button> lstTxt = new List<Button>
{
bttnSpring, bttnSummer, bttnAutumn, bttnWinter
};
//Wiring up event handlers in run time
foreach (Button txt in lstTxt)
{
txt.MouseEnter += button_MouseEnter;
txt.MouseLeave += button_MouseLeave;
}
}
// Sets up different background colors for TextBoxes
//* Static values for the color of each button need
//to be added.
//**Not what I was trying to accomplish
//**This needs to go somewhere else
void button_MouseEnter(object sender, EventArgs e)
{
try
{
// Event handlers always pass the parameter "sender" in as an object.
// You have to downcast it back to the actual type.
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
// stkColor.Push(txt.BackColor);
//txt.BackColor = Color.Red;
bttnName = txt.Name;
if (bttnName == bttnNameSpring)
{
txt.BackColor = Color.LightGreen;
}
else if (bttnName == bttnNameSummer)
{
//txt.BackColor = Color.Red;
txt.BackColor = Color.Red;
}
else if (bttnName == bttnNameAutumn)
{
txt.BackColor = Color.Yellow;
}
else if (bttnName == bttnNameWinter)
{
txt.BackColor = Color.Cyan;
}
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
//Handler for mouse leaving the button
void button_MouseLeave(object sender, EventArgs e)
{
try
{
Button txt = (Button)sender;
//txt.BackColor = stkColor.Pop();
}
catch (Exception ex)
{
MessageBox.Show("Error:\n " + ex.Message);
}
}
}
}
}
Alright, so I'm just trying to create a simple program that changes the background colors of these buttons to some plain colors when you mouse over them. I had the same thing working using TextBox, but I need to get it working with button. I changed everything over to use the Button class, and it seems to have all the same functionality, but now the program runs, but nothing happens when you mouse over the buttons.
I'm pretty new to c#, stack exchange, and only slightly less so to programming in general, so sorry if I'm dinking up on etiquette/formatting my questions, etc.
I think you are trying to reference your buttons title when you are actually calling the button name
Changing:
String bttnName = null;
String bttnNameSpring = "Spring";
String bttnNameSummer = "Summer";
String bttnNameAutumn = "Autumn";
String bttnNameWinter = "Winter";
Button txt = (Button)sender;
To:
String bttnName = null;
String bttnNameSpring = "bttnSpring";
String bttnNameSummer = "bttnSummer";
String bttnNameAutumn = "bttnAutumn";
String bttnNameWinter = "bttnWinter";
Causes the code to work.
If you do infact want to use the "Spring", "Summer" etc reference than i would suggest changing
bttnName = txt.Name;
to
bttnName = txt.Text;
And ensure that the Text of the labels is set correctly