I need to populate a listbox from a text file at startup. I also need to have the firt 2 lines eliminated from the listbox along with all blank lines, but that isn't to important right now. I am currently stuck at getting the listbox populated at all. Here is my code so far:
struct CDCLocationEntry
{
public string name;
}
public partial class StartupForm : Form
{
private List<CDCLocationEntry> CDCList = new List<CDCLocationEntry>();
public StartupForm()
{
InitializeComponent();
}
private void ReadFile()
{
try
{
StreamReader inputFile;
string line;
CDCLocationEntry entry = new CDCLocationEntry();
inputFile = File.OpenText("P3S1 Data File For Import.txt");
while (!inputFile.EndOfStream)
{
line = inputFile.ReadLine();
CDCList.Add(entry);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void DisplayText()
{
foreach (CDCLocationEntry entry in CDCList)
{
CDCLocationListBox.Items.Add(entry.name);
}
}
private void StartupForm_Load(object sender, EventArgs e)
{
ReadFile();
DisplayText();
}
visual studio is say my problem is here:
struct CDCLocationEntry
{
public string name;
}
the message I'm getting is:
Warning 1 Field 'Project_3___Section_1.CDCLocationEntry.name' is never
assigned to, and will always have its default value null
none of my notes or online help is giving me an answer for this.
Any help that you can provide would be greatly appreciated
You need to create a CDCLocationEntry instance inside the loop and assign, at this instance property name, the line coming from your file
inputFile = File.OpenText("P3S1 Data File For Import.txt");
while (!inputFile.EndOfStream)
{
CDCLocationEntry entry = new CDCLocationEntry();
entry.name = inputFile.ReadLine();
CDCList.Add(entry);
}
Your actual code creates just one instance of CDCLocationEntry outside the loop and, without assigning anything to the name property, adds this same instance in every loop.
Related
I am new and trying to do something in c# but I dont know how to solve this prbolem.
My MainWindow.xaml.cs I have a RichTextBox with name RTB that I wanna save into text file.
I created new file Saving.cs where I would write every thing that I need for saving.
This is my code.
Saving.cs
public string VarName = "";
public void Save()
{
MainWindow main = new MainWindow();
TextRange range = new TextRange(main.RTB.Document.ContentStart, main.RTB.Document.ContentEnd);
FileStream stream = new FileStream(VarName, FileMode.Create);
range.Save(stream, DataFormats.Text);
stream.Close();
}
MainWindow.xaml.cs
private void Button_Save(object sender, RoutedEventArgs e)
{
saveDoc.VarName = SaveName.Text + ".txt";
saveDoc.Save();
}
Everything works fine except that there is nothing in saved document.
My problem is that I really dont know how to acces RTB from different file. It works when I put this code into MainWindow.xaml.cs but not when its in different file like Saving.cs.
I also dont know if its ok to have this in my Saving.cs "MainWindow main = new MainWindow();" or how to aproach this problem.
Thanks for your help kind stranger.
I hope these code snippets can help to solve your problem
MainWindow.xaml.cs :
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: Please dont forget about OOP,
// dont use 'public' mode on class fields (VarName)
SaveDoc.MyProperty = SaveName.Text + ".txt";
TextRange range = new TextRange(RTB.Document.ContentStart,RTB.Document.ContentEnd);
//You can pass this 'range' field as a parameter to Class 'SaveDoc'
SaveDoc.Save(range);
}
Saving.cs :
class SaveDoc
{
private static string VarName;
//Use Properties to access fields from another classes
public static string MyProperty
{
get { return VarName; }
set { VarName = value; }
}
// Here you can pass the 'range' field from MainWindow as a parameter
public static void Save(TextRange range)
{
FileStream stream = new FileStream(VarName, FileMode.Create);
range.Save(stream, DataFormats.Text);
stream.Close();
}
}
Also you can do like this:
MainWindow.xaml.cs :
private void Button_Click(object sender, RoutedEventArgs e)
{
// Note: Please dont forget about OOP,
// dont use 'public' mode on class fields (VarName)
SaveDoc.MyProperty = SaveName.Text + ".txt";
string range = new TextRange(RTB.Document.ContentStart,RTB.Document.ContentEnd).Text;
//You can pass this 'range' field as parameter to Class 'SaveDoc'
SaveDoc.Save(range);
}
Saving.cs :
class SaveDoc
{
private static string VarName;
//Use Properties to access fields from another classes
public static string MyProperty
{
get { return VarName; }
set { VarName = value; }
}
// Here you can pass the 'range' field from MainWindow as a parameter
public static void Save(string range)
{
// Standart algorithm to write something in file:
FileStream stream = new FileStream(VarName, FileMode.Create);
//convert string to bytes
byte[] buf = Encoding.Default.GetBytes(range);
// writing an array of bytes to a file
stream.Write(buf, 0, buf.Length);
stream.Close();
}
}
I'm trying to pass a value(an element id) from a WinForm back to the Command.cs file but I'm getting an error:
System.NullReferenceException: Object reference not set to an instance of an object.
at BatchSheetMaker.Command.Execute(ExternalCommandData commandData, String& message, ElementSet elements)
I'm following the youtube tutorial here and it seems fairly easy and straight forward but passing back to the Command.cs is another layer of complexity.
I have the Command.cs code wrapped in a try/catch block which just tells me that there's nullReferenceException however it doesn't tell me which line it's occurring at. I've looked around but havn't found any tips on how to make the debug show the error line. If anyone has any other pointers, that'd be helpful.
Form1.cs
public partial class Form1 : System.Windows.Forms.Form
{
private UIApplication uiapp;
private UIDocument uidoc;
private Autodesk.Revit.ApplicationServices.Application app;
private Document doc;
private string myVal;
public string MyVal
{
get { return myVal; }
set { myVal = value; }
}
public Form1(ExternalCommandData commandData)
{
InitializeComponent();
uiapp = commandData.Application;
uidoc = uiapp.ActiveUIDocument;
app = uiapp.Application;
doc = uidoc.Document;
}
public delegate void delPassData(System.Windows.Forms.ComboBox text);
private void Form1_Load(object sender, EventArgs e)
{
//Create a filter to get all the title block types.
FilteredElementCollector colTitleBlocks = new FilteredElementCollector(doc);
colTitleBlocks.OfCategory(BuiltInCategory.OST_TitleBlocks);
colTitleBlocks.WhereElementIsElementType();
foreach(Element x in colTitleBlocks)
{
comboBox1TitleBlockList.Items.Add(x.Name);
}
}
private void button1Continue_Click(object sender, EventArgs e)
{
MyVal = comboBox1TitleBlockList.Text;
}
Command.cs
Form1 form1 = new Form1(commandData);
String elementString = form1.MyVal.ToString();
Element eFromString = doc.GetElement(elementString);
ElementId titleBlockId = eFromString.Id;
ViewSheet sheet = ViewSheet.Create(doc, titleBlockId);
Run your entire add-in inside the Visual Studio debugger and step through your code line by line. That will show you exactly where the exception is thrown and enable you to easily identify what is causing the problem.
Changed my code to this and it started working:
form1.cs
public string MyVal;
//{
//get { return myVal; }
//set { myVal = value; }
//}
this link was helpful along with tutorials on youtube on how to pass values from form to form.
I am reading a file into a list and then want a button to pull a random entry from the list. I can do this in VB but am fairly new to c#. I know I have to make the list public, but I'm getting increasingly frustrated.
The code below reads the file to a list and then a listbox.
namespace texttoarray
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
var list = new List<string>();
var file = new StreamReader(#"list.txt");
while ((line = file.ReadLine()) != null)
{
list.Add(line);
counter++;
}
listBox2.DataSource = list;
var rnd = new Random();
}
}
}
If you want to process some information inside one method and use this processed information inside another method, you can:
pass the information as an argument to the second method
keep the information inside your class and use it inside any method
I'll assume the second approach for you, so you can do something like this:
static class Program
{
// list inside your class with the information you need
private static List<string> fileLines;
private static void Main(string[] args)
{
// call the method to read your file and create the list
FirstMethod();
// second method to get a random line, in this case, will return the string
var result = SecondMethod();
Console.WriteLine(result);
Console.ReadLine();
}
private static void FirstMethod()
{
// with this approach you can load one line per string inside your List<>
var yourFile = File.ReadAllLines("C:\\test.txt");
fileLines = new List<string>(yourFile);
}
private static string SecondMethod()
{
// random number starting with 0 and maximum to your list size
var rnd = new Random();
return fileLines[rnd.Next(0, fileLines.Count)];
}
}
I'm making a console terminal using ListView for my custom server.
It writes any string that was given to it from the same class Main but refuses if its from another Misc.
Heres a gif of the following code in action
The first part of the gif is from myFunction(). As you can see, the messagebox shows that str in stringToConsole() contains a string("report 1" and "report 2") but it wouldnt add it.
Second part of the gif is from Execute_Click event. As you can see, again the messagebox shows that str in stringToConsole() contains a string(whatever i type) and it would add it
Following code is in Class Misc.
Following code's strings are not able to be added.
public static string myFunction()
{
Main myClass = new Main();
myClass.stringToConsole("report 1", "ConsoleList");
Thread.Sleep(2000); // emulate work
myClass.stringToConsole("report 2", "ConsoleList");
return "string";
}
Following codes are inside the form class Main.
private void startupProcedure()
{
label1.Text = Misc.myFunction();
}
This add strings to the ListView(Console List)
public void stringToConsole(string str, string destination)
{
if (destination == "ConsoleList")
{
// to check if str has a value
MessageBox.Show(str); // string does have a value
ConsoleList.Items.Add(str); // refuse to use str from myFunction()
}
}
Following code's strings are able to be added.
private void Execute_Click(object sender, EventArgs e)
{
executeCommandLine(CommandLine.Text, "ConsoleList");
CommandLine.Clear();
}
public void executeCommandLine(string commandLine, string destination)
{
stringToConsole(commandLine, destination); // this shows in Listview
}
A very similar question was asked some hours ago. You have a very, very basic problem:
Main myClass = new Main();
You are instantiating a new Main form, however, you are never showing it or using it outside the function's scope, hence, you are not modifying the Main instance you want to modify.
An easy way to do this would be to pass the Main instance to the function:
public static string myFunction(Main formInstance)
{
formInstance.stringToConsole("report 1", "ConsoleList");
Thread.Sleep(2000); // emulate work
formInstance.stringToConsole("report 2", "ConsoleList");
return "string";
}
private void startupProcedure()
{
label1.Text = Misc.myFunction(this);
}
I need to add my list to my listbox. I searched through all the questions on this site but none work I always get things like listbox1.spelers in my listbox.
Here is the code I have now.
private void btnAdd_Click(object sender, EventArgs e)
{
Speler speler1 = new Speler(tbNaam.Text, tbAge.Text);
List<Speler> spelers = new List<Speler>();
spelers.Add(speler1);
listBox1.DataSource = spelers;
}
Also tried with the ToArray but it still didn't work.
SOLVED
You're re-binding the control to a list of exactly one element every time. So the control will only ever have one element.
Keep the list in a higher scope. For example, if this class is persistent in memory (that is, not a web application) then make it a class-level member:
private List<Speler> spelers = new List<Speler>();
private void btnAdd_Click(object sender, EventArgs e)
{
Speler speler1 = new Speler(tbNaam.Text, tbAge.Text);
spelers.Add(speler1);
listBox1.DataSource = spelers;
// maybe call listBox1.DataBind() here? it's been a while since I've had to use forms
}
That way you're always adding another element to the same list, instead of creating a new list every time.
If you are using Windows Forms application, you can use a BindingDource:
Speler speler1 = new Speler(tbNaam.Text, tbAge.Text);
List<Speler> spelers = new List<Speler>();
spelers.Add(speler1);
var bs = new BindingSource();
bs.DataSource = spelers;
listBox1.DataSource = bs;
Good example is here : Console App
using System;
namespace Enumeration
{
using System;
using System.Collections;
// implements IEnumerable
class ListBoxTest : IEnumerable
{
private string[] strings;
private int ctr = 0;
// private nested implementation of ListBoxEnumerator
private class ListBoxEnumerator : IEnumerator
{
// member fields of the nested ListBoxEnumerator class
private ListBoxTest currentListBox;
private int index;
// public within the private implementation
// thus, private within ListBoxTest
public ListBoxEnumerator(ListBoxTest currentListBox)
{
// a particular ListBoxTest instance is
// passed in, hold a reference to it
// in the member variable currentListBox.
this.currentListBox = currentListBox;
index = -1;
}
// Increment the index and make sure the
// value is valid
public bool MoveNext()
{
index++;
if (index >= currentListBox.strings.Length)
return false;
else
return true;
}
public void Reset()
{
index = -1;
}
// Current property defined as the
// last string added to the listbox
public object Current
{
get
{
return(currentListBox[index]);
}
}
} // end nested class
// Enumerable classes can return an enumerator
public IEnumerator GetEnumerator()
{
return (IEnumerator) new ListBoxEnumerator(this);
}
// initialize the listbox with strings
public ListBoxTest(params string[] initialStrings)
{
// allocate space for the strings
strings = new String[8];
// copy the strings passed in to the constructor
foreach (string s in initialStrings)
{
strings[ctr++] = s;
}
}
// add a single string to the end of the listbox
public void Add(string theString)
{
strings[ctr] = theString;
ctr++;
}
// allow array-like access
public string this[int index]
{
get
{
if (index < 0 || index >= strings.Length)
{
// handle bad index
}
return strings[index];
}
set
{
strings[index] = value;
}
}
// publish how many strings you hold
public int GetNumEntries()
{
return ctr;
}
}
public class EnumerationTester
{
public void Run()
{
// create a new listbox and initialize
ListBoxTest currentListBox =
new ListBoxTest("Hello", "World");
// add a few strings
currentListBox.Add("Who");
currentListBox.Add("Is");
currentListBox.Add("John");
currentListBox.Add("Galt");
// test the access
string subst = "Universe";
currentListBox[1] = subst;
// access all the strings
foreach (string s in currentListBox)
{
Console.WriteLine("Value: {0}", s);
}
}
[STAThread]
static void Main()
{
EnumerationTester t = new EnumerationTester();
t.Run();
}
}
}