How do invoke a message box with a listbox item - c#

I'm working on an application that has the user fill out the four fields on the left and click the "Add Car" button and the Model, Color, and Year would appear as an listbox item and once they select that listbox item a messagebox would appear giving the user the price they wrote in the price field earlier. I've got everything to work except having the messagebox appear when I click on the listbox item. I'm not sure why it's not working.
Here I've included my code for this project. I used Visual Studio 2017 and the type of project is a Visual C# Windows Form App project if that helps:
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 MIS_312_Extra_Challenge_Project
{
public partial class Form1 : Form
{
string model, color, details = "", AllDetails = "", models = "";
int year;
double price;
public Form1()
{
InitializeComponent();
}
private void btn_addCar_Click(object sender, EventArgs e)
{
model = txtModel.Text;
color = txtColor.Text;
year = Convert.ToInt32(txtYear.Text);
price = Convert.ToDouble(txtPrice.Text);
details = model + " " + color + " " + year + Environment.NewLine;
AllDetails = AllDetails + price + " " + Environment.NewLine;
models = models + model + " " + Environment.NewLine;
list_carDetails.Items.Add(details);
txtModel.Clear();
txtColor.Clear();
txtYear.Clear();
txtPrice.Clear();
txtModel.Clear();
}
private void btn_Exit_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void list_carDetails_SelectedIndexChanged_1(object sender, EventArgs e)
{
}
private void list_carDetails_SelectedIndexChanged(object sender, EventArgs e)
{
string[] all = AllDetails.Split();
string[] m = models.Split();
string[] modelName = { };
int i;
foreach (var car in list_carDetails.SelectedItems)
{
string details = car.ToString();
modelName = details.Split();
}
for(i=0;i<m.Length;i++)
{
if (string.Compare(modelName[0],m[i])== 0)
{
MessageBox.Show("The price of the " + modelName[0] + " is $" + all[i]);
}
}
}
}
}

Related

StreamWriter only shows the last input in saved textfile, first one becomes blank on new line

Instructions:
As I enter: Last Name, First Name, ID#, Class and Grade. Press "OK". Press "Load" (the entered information shows down below in a readonly TextBox). Now I enter it all again, Press "OK" and "Load" again (now you I see two lines of information).
Here is an image of my form:
What happens:
When I hit Save As, save my txt-file somewhere and open it. It will show the last input on the first line, and a blank on the secound (which seems to be the first input, but now its blank)
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.IO;
namespace StudentGrades
{
public partial class Form1 : Form
{
static string status;
public Form1()
{
InitializeComponent();
writeButton.Enabled = false;
}
private void readButton_Click(object sender, EventArgs e)
{
using (StreamReader sr =
new StreamReader(#"C:\Users\User\Documents\Visual Studio 2017\Projects\StudentGrades\StudentGrades\TextFile.txt"))
{
textBoxReadGrades.AppendText(sr.ReadToEnd());
}
writeButton.Enabled = true;
}
private async void writeButton_Click(object sender, EventArgs e)
{
using (SaveFileDialog sfd = new SaveFileDialog() { Filter =
"TextDocuments|*txt.", ValidateNames = true})
{
if (sfd.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(sfd.FileName))
{
await sw.WriteLineAsync(textBoxFirstName.Text +
" " + textBoxLastName.Text +
" " + textBoxID.Text +
" " + textBoxClass.Text +
" " + textBoxGrade.Text);
MessageBox.Show("You have successfully saved", "Message",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
private void okButton_Click(object sender, EventArgs e)
{
using (StreamWriter sw =
new StreamWriter(#"C:\Users\User\Documents\Visual Studio 2017\Projects\StudentGrades\StudentGrades\TextFile.txt"))
sw.WriteLine(textBoxFirstName.Text +
" " + textBoxLastName.Text +
" " + textBoxID.Text +
" " + textBoxClass.Text +
" " + textBoxGrade.Text + "\n");
status = StatusLabel.Text =
"Entry Saved";
writeButton.Enabled = false;
}
private void GetInfo (string fileName)
{
textBoxReadGrades.AppendText(File.ReadAllText(fileName));
}
private void ExitButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
You may use AppendText method to append text to the existing file instead of overwriting:
using (StreamWriter sw = File.AppendText(sfd.FileName))
{
...
}

How to make a customized progressbar in c#

I would like to learn how to make a progressbar like the one shown in this video.
I tried to replicate it in VS C#, but I get the error:
C# Property or indexer cannot be assigned to -- it is read only
If I try using if (txProgressBar.Text.Length == 85), I will get this in the TextBox (txProgressBar)
System.Windows.Forms.TextBox, Text: System.Windows.Forms.TextBox, Text: Syst...██
Textbox Progressbar Tutorial VB 2010
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 CustomizedProgressBar
{
public partial class Form1 : Form
{
int last = 1;
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (txProgressBar.Text.Length = "85")
{
timer1.Stop();
MessageBox.Show("Counted!");
}else
{
if (last == 1)
{
txProgressBar.Text = txProgressBar + "█";
last = 2;
}
else
{
txProgressBar.Text = txProgressBar.Text + "█";
last = 1;
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
txProgressBar.Text = "";
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Start();
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Stop();
}
}
}
Your line:
txProgressBar.Text = txProgressBar + "█";
should be
txProgressBar.Text = txProgressBar.Text + "█"; or txProgressBar.Text &= "█";
I realized what was the problem. The txProgressBar.Text = txProgressBar + "█"; was missing the *.Text. That solved the problem and the message is shown as well.

Winsock with C# Severity Code ERROR: The name 'DataInput' does not exist in the current context

I'm new to coding in c#,My Project is connecting server and client using Winsock control. I am doing exactly this program http://www.go4expert.com/articles/winsock-c-sharp-t3312/ to connect server and client.
form:
enter image description here
code:
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 Winsock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.w1.Error += new AxMSWinsockLib.DMSWinsockControlEvents_ErrorEventHandler(this.w1_Error);
this.w1.ConnectEvent += new System.EventHandler(this.w1_ConnectEvent);
this.w1.DataArrival += new AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEventHandler(this.w1_DataArrival);
}
Boolean isConnect = false;
private void w1_ConnectEvent(object sender, EventArgs e)
{
DataInput.Text += "\n - Connect Event : " + w1.RemoteHostIP;
isConnect = true;
}
public void w1_Error(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ErrorEvent e)
{
DataInput.Text += "\n- Error : " + e.description;
isConnect = false;
}
private void w1_DataArrival(object sender, AxMSWinsockLib.DMSWinsockControlEvents_DataArrivalEvent e)
{
String data = "";
Object dat = (object)data;
w1.GetData(ref dat);
data = (String)dat;
DataInput.Text += "\nServer - " + w1.RemoteHostIP + " : " + data;
}
private void send_Click(object sender, EventArgs e)
{
try
{
if (isConnect)
{
w1.SendData(SendText.Text);
DataInput.Text += "\nClent(You ;-) : " + SendText.Text;
SendText.Text = "";
}
else
MessageBox.Show("You are not connect to any host ");
}
catch (AxMSWinsockLib.AxWinsock.InvalidActiveXStateException g)
{
DataInput.Text += "\n" + g.ToString();
}
catch (Exception ex)
{
DataInput.Text += "\n" + ex.Message;
}
}
private void disconnect_Click(object sender, EventArgs e)
{
w1.Close();
w1.LocalPort = Int32.Parse(portText.Text);
w1.Listen();
DataInput.Text += "\n - Disconnected";
}
private void Connect_Click(object sender, EventArgs e)
{
try
{
w1.Close();
w1.Connect(IPText.Text, portText.Text);
}
catch (System.Windows.Forms.AxHost.InvalidActiveXStateException g)
{
DataInput.Text += "\n" + g.ToString();
}
}
private void w1_ConnectionRequest(object sender, AxMSWinsockLib.DMSWinsockControlEvents_ConnectionRequestEvent e)
{
if (isConnect == true)
{
w1.Close();
}
w1.Accept(e.requestID);
isConnect = true;
DataInput.Text += "\n - Client Connected :" + w1.RemoteHostIP;
}
}
}
Error
The name 'DataInput' does not exist in the current context
I can't seem to find a solution to this problem by searching the web Please help me :(
Create a Textbox Named "DataInput" on your form.

C# form instantly closing

All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.

C# xmldataprovider insert node

I am trying to write an editor for an xml config file. I have the xml file bound to a listview and selecting an element and then clicking edit allows you to edit an element. When the user clicks save, a delegate is called which updates the element within the xml document. I have tried to do the updating in various ways including appendnode, prependnode, insertafter, and replace child. I have gotten them all working without any compile time or runtime errors, yet they don't update the xmldataprovider or the listview. It's probably just something simple that I am missing but I am having trouble figuring out what it is. Can someone please help?
Thanks,
Brian
If it helps, here's the source code of my main form (the one with the listview)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.IO;
namespace g2config
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public XmlDataProvider dp;
string cfgfile;
public managecmpnts manage_components;
public delegate void managecmpnts(int id, XmlElement component);
public MainWindow()
{
InitializeComponent();
dp = this.FindResource("configfile") as XmlDataProvider;
cfgfile = "C:\\Users\\briansvgs\\Desktop\\g2config\\g2config\\bin\\Debug\\g2config.pxml";
if(Environment.GetCommandLineArgs().Count() > 1)
{
string path = Environment.GetCommandLineArgs().ElementAt(1);
//MessageBox.Show("Path: " + path);
cfgfile = path;
}
if (File.Exists(cfgfile))
{
dp.Source = new Uri(cfgfile, UriKind.RelativeOrAbsolute);
}
else
{
MessageBox.Show("config file not found");
}
this.Title = this.Title + " (" + cfgfile + ") ";
}
public void browsedir( object sender, EventArgs e)
{
System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
ofd.Filter = "PXML Files (*.pxml)|*.pxml"; ;
//http://www.kirupa.com/net/using_open_file_dialog_pg4.htm
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) //how to browse dirs instead of files?????
{
startpath.Text = ofd.FileName;
}
}
public void newcomponent(object sender, RoutedEventArgs e)
{
componentsettings new_cmpnt = new componentsettings();
new_cmpnt.Title = "Add Component";
new_cmpnt.ShowDialog();
}
public void editcomponent(object sender, RoutedEventArgs e)
{
int selected = components.SelectedIndex;
XmlElement current = (XmlElement)components.Items.CurrentItem;
componentsettings edit_cmpnt = new componentsettings(current);
edit_cmpnt.cmpnt_mgr.manage_components += new manager.mngcmpnts(test);
edit_cmpnt.Title = "Edit Component";
edit_cmpnt.ShowDialog();
}
private void browsedir(object sender, RoutedEventArgs e)
{
System.Windows.Forms.FolderBrowserDialog directory;
directory = new System.Windows.Forms.FolderBrowserDialog();
directory.Description = "Please select the folder containing your g2 configuration (pxml) files. Default is C:\\Program Files\\Exacom, Inc.";
directory.ShowDialog();
startpath.Text = directory.SelectedPath;
}
private void save(object sender, RoutedEventArgs e)
{
MessageBox.Show(dp.Source.ToString());
if(File.Exists(cfgfile + ".old"))
{
File.Delete(cfgfile + ".old");
}
File.Move(cfgfile, cfgfile + ".old");
dp.Document.Save(cfgfile);
}
private void remove(object sender, RoutedEventArgs e)
{
XmlNode component = dp.Document.DocumentElement["Components"].ChildNodes[components.SelectedIndex];
dp.Document.DocumentElement["Components"].RemoveChild(component);
}
private void temp(object sender, RoutedEventArgs e)
{
MessageBox.Show(dp.Document.DocumentElement["Components"].ChildNodes[components.SelectedIndex].InnerText.ToString()); //will this give me trouble????? Probably not since it's my config, but...
}
private void test(int id, XmlElement testelement)
{
//dp.Document.DocumentElement["Components"].ChildNodes[id] = testelement;
//XmlNode testnode = dp.Document.DocumentElement["Components"].ChildNodes[id + 1];
//XmlNode testnode = testelement;
MessageBox.Show(testelement.OuterXml.ToString());
//dp.Document.DocumentElement["Components"].InsertAfter(dp.Document.DocumentElement["Components"].ChildNodes[0], testelement);
//dp.Document.DocumentElement["Components"].RemoveChild(testelement);
//dp.Document.DocumentElement["Components"].ReplaceChild(testnode, dp.Document.DocumentElement["Components"].ChildNodes[id]);
dp.Document.DocumentElement["Components"].PrependChild(testelement);
//dp.Document.NodeChanged();
//dp.Document.DocumentElement["Components"].CloneNode(true);
dp.Document.DocumentElement["Components"].AppendChild(testelement);
//dp.Document.
//MessageBox.Show(dp.Document.OuterXml.ToString());
//MessageBox.Show(dp.Document.DocumentElement["Components"].FirstChild.AppendChild(testelement).OuterXml.ToString());
}
}
}
JMSA. Thank you for the suggestion. I was playing around with it today and I found a solution. It's a little messy, but it works. I copy one of the present nodes and then clear all of the values. Here is the code if anyone is interested.
private void add(object sender, RoutedEventArgs e)
{
System.Xml.XmlNode test = configfile.Document.DocumentElement["Components"].FirstChild;
System.Xml.XmlNode testclone = test.Clone();
for (int i = 0; i < testclone.ChildNodes.Count; i++)
{
testclone.ChildNodes[i].RemoveAll();
}
configfile.Document.DocumentElement["Components"].AppendChild(testclone);
components.SelectedItem = components.Items.Count + 1;
}
My suggestion would be to create a class for each element by using a composite pattern, lazy loading the XML doc in the class and perform operations as you need. Then again save it. Quite a handful though.

Categories