C# form instantly closing - c#

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.

Related

Async coding in C#, not able to get the second element to work

The goal of this project in C# is to browse for a txt file in each box (that coding works) and hit submit and each side will run to select the top ten repeated words in each listbox. I have got most of the code to work but I can only get book 1 side to run and not book 2. Attached is the code as well as the image to help understand! Using Windows Desktop (.NET) application.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Asynchronous_Program
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e) => Close();
private async void btnSubmit_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
listBox2.Items.Clear();
List<Task> tasks = new List<Task>();
var file = openFileDialog1.FileName;
var wordTask = ReadBook(file);
tasks.Add(wordTask);
await Task.WhenAll(tasks);
//Other operations after this has finished
}
private async Task ReadBook(string filename)
{
var lines = await Task.FromResult(File.ReadAllLinesAsync(filename));
var arrayLinesWithoutPunctuation =
lines.Result.Where(x => x != String.Empty)
.AsParallel()
.Select(x => x.ToLower().Trim().Replace(",", "").Replace("{", ""));
var arrayOfWords = arrayLinesWithoutPunctuation.SelectMany(x => x.Split(" "));
Dictionary<string, int> wordDic = new Dictionary<string, int>();
arrayOfWords.ToList().ForEach(x =>
{
if (wordDic.ContainsKey(x))
{
wordDic[x] += 1;
}
else
{
wordDic.Add(x, 1);
}
});
var top10 = wordDic.Where(x =>
!string.IsNullOrWhiteSpace(x.Key)).OrderByDescending(x => x.Value).Take(10);
foreach(var word in top10)
{
listBox1.Items.Add(word.Key + " - " + word.Value);
listBox2.Items.Add(word.Key + " - " + word.Value);
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
DialogResult result = this.openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtFileName.Text = openFileDialog1.FileName.Split("\\").LastOrDefault();
}
}
private void btnBrowse2_Click(object sender, EventArgs e)
{
DialogResult result = this.openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
txtFileName2.Text = openFileDialog2.FileName.Split("\\").LastOrDefault();
}
}
}
}

why can't I add a new List object in button event

why can't I add a new item/object to my list in button (or combobox etc.) events? I mean, the events don't see my list if it's outside of the brackets...it's underlined in red... can you help me?
long story short: i want to add a new object by clicking the button
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.Xml.Serialization;
using System.IO;
namespace Samochody
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
List<Samochod> ListaSamochodow = new List<Samochod>();
comboBox1.DataSource = ListaSamochodow;
comboBox1.DisplayMember = "Marka";
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
ListaSamochodow.Add(new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text)));
}
catch (Exception oException)
{
Console.WriteLine("Aplikacja wygenerowała następujący wyjątek: " + oException.Message);
}
}
I think you should instantiate your list globally and not under Form1_Load event.
that way it will be accessible all around your class (the window in this case).
This seems to work fine. You might need to set your textboxes to contain valid values when you start the form. also make sure that you make the list visible throughout your form1 class.
namespace Samochody
{
public partial class Form1 : Form
{
// make sure your list looks like this, created outside your functions.
List<Samochod> ListaSamochodow = new List<Samochod>();
public Form1()
{
InitializeComponent();
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
textBox1.Text = "string here";
textBox2.Text = "string here";
textBox3.Text = "100";
}
private void Form1_Load(object sender, EventArgs e)
{
XmlRootAttribute oRootAttr = new XmlRootAttribute();
XmlSerializer oSerializer = new XmlSerializer(typeof(List<Samochod>), oRootAttr);
StreamWriter oStreamWriter = null;
oStreamWriter = new StreamWriter("samochody.xml");
oSerializer.Serialize(oStreamWriter, ListaSamochodow);
}
private void button1_Click_1(object sender, EventArgs e)
{
Samochod s = new Samochod(textBox1.Text, textBox2.Text, Convert.ToInt32(textBox3.Text));
ListaSamochodow.Add(s);
label1.Text = "the amount in your list is " + ListaSamochodow.Count.ToString();
}
}
}

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.

C# Windows Application LOC_Counter

Hey I want to create a windows application that should display the total lines, Blank lines and commented lines. I am able to calculate Total Lines, Can any one help me with the logic for blank lines and commented lines!
I want to count the Lines Of Code, for any file, i.e .html, .css, .cs, etc.
Also if possible I want the result to be exported to a Excel File!
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 Line_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
textbox1.Clear();
textbox2.Clear();
if (ofd.ShowDialog() == DialogResult.OK)
{
string strFilename = ofd.FileName;
textbox1.Text = Path.GetFileName(strFilename);
StreamReader sr = File.OpenText(strFilename);
int nLineCount = 0;
while (sr.ReadLine() != null)
{
nLineCount++;
}
textbox1.Text = nLineCount.ToString("0,0");
sr.Close();
}
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I want more text boxes that should display count of blank lines, Commented lines, and finally the total count (i.e. subtracting the no. of blank lines and commented lines from total no of lines)
If Possible single button_click for each or all in one.enter image description here
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 LOC_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void getFileList(string directory)
{
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
getFileList(dir);
}
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
StreamReader sr = File.OpenText(file);
int nLineCount = 0;
string str = string.Empty;
while (!sr.EndOfStream)
{
str = sr.ReadLine();
if (str != null && str.Length > 0 && (str.Length > 2 && str.Substring(0, 2) != "//") && (str.Length > 3 && str.Substring(0, 4) != "<!--"))
nLineCount++;
}
lstbxResult.Items.Add(file + " Line count - " + nLineCount);
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
lstbxResult.Items.Clear();
getFileList(FBD.SelectedPath);
}
}
public static void ExportToExcel(ListBox lst, string excel_file)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(excel_file);
//write rows to excel file
for (int i = 0; i < (lst.Items.Count - 1); i++)
{
wr.Write(lst.Items[i].ToString() + "\t");
wr.WriteLine();
}
//close file
wr.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

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