Access RichTextBox from another class - c#

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();
}
}

Related

Pass along global variable to class

I am trying to pass a string to a public class (customPanel).
But the "teststring" is never passed on and written to the testfile.txt?
The testfile.txt writes an empty string.
private void button1_Click(object sender, EventArgs e)
{
customPanel cp = new customPanel();
cp.getinfo = "teststring";
}
public class customPanel : System.Windows.Forms.Panel
{
public String getinfo { get; set; }
public customPanel() { InitializeComponent(); }
private void InitializeComponent()
{
String gi = getinfo;
System.IO.FileStream fs = new System.IO.FileStream("C:/folder1/testfile.txt", System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
System.IO.StreamWriter writer = new System.IO.StreamWriter(fs);
writer.WriteLine(gi); writer.Close(); fs.Close();
}
}
The problem you’re having is happening because of the order of execution of your code.
Basically when you call new customPanel(), that’s when the constructor method controlPanel() is going to be called. So when you set the getInfo value, your InitializeComponent() method was already called.
Without knowing better about your context, the easy solution would be to pass the string as a parameter to your constructor. Basically switch controlPanel() to receive a string variableName as a parameter, like this controlPanel(string variableName)and then before calling InitializeComponent(); set the value of the property with a this.getInfo = variableName;.
Let me know if this helped!
Take care.

How can the scope be changed in a WinForms app to carry variables from a method to an object sender?

I am trying to carry the variables from the array over to the button click action. I can't find the way to set the scope to allow for this to work.
I have tried changing the modifiers to public, private, static, void, string, string[] etc.
I have also made all of the objects in the WinForms app set to Public
public partial class AutoPay : Form
{
public AutoPay()
{
InitializeComponent();
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
dateAndTime = DateTime.Now.ToString();
fileNumber = txtFileNumber.Text;
string[] headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(headerArray[0], headerArray[1]);
}
}
the headerArray[0] under the BtnSave_Click action has the red line under it showing that it is outside of the scope.
Try declaring the headerArray as a Property of the class
As was mentioned... you need to declare the headerArray outside the method... Also... it looks like you are trying to add information to the array before the array has information... try it this way(there are many other ways to do this too ;) ):
public partial class AutoPay : Form
{
private string[] headerArray; // <-- declare it here...
public AutoPay()
{
InitializeComponent();
headerArray = new string[2]; // <-- sometimes the normal way to initialize...
}
public void HeaderInformation(string dateAndTime, string fileNumber)
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = dateAndTime;
headerArray[1] = fileNumber;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation(DateTime.Now.ToString(), txtFileNumber.Text);
}
}
or
public void HeaderInformation()
{
// reinitialize headerArray for safety....
headerArray = new string[2];
headerArray[0] = DateTime.Now.ToString();
headerArray[1] = txtFileNumber.Text;
}
public void BtnSave_Click(object sender, EventArgs e)
{
HeaderInformation();
}

Set image in Picture-box from Business Logic Class to Main application Class

I write a c# code according to software architecture. In business logic layer I implement a code by which I can extract data from wikipedia api to get image. I want to show it on application layer which is Form1.cs. But it is not working at all. My code for getting the image from Wikipedia looks like this:
public class ImageService
{
private string _baseUrl = "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&pithumbsize=400&titles={0}";
public string GetImage(string name)
{
string requestUrl = string.Format(_baseUrl, name);
string result;
using (WebClient client = new WebClient())
{
var response = client.DownloadString(new Uri(_baseUrl));
var responseJson = JsonConvert.DeserializeObject<ImgRootobject>(response);
var firstKey = responseJson.query.pages.First().Key;
result = responseJson.query.pages[firstKey].thumbnail.source;
string Image_title = responseJson.query.pages[firstKey].title;
}
return result;
}
}
My Form1.cs is:
public partial class Form1 : Form
{
private readonly ImageService _imageService;
public Form1()
{
_imageService = new ImageService();
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.LoadAsync(_imageService);
}
}
You didn't call the GetImage method from ImageService which returns the string. The LoadAsync method of the PictureBox accept one string as it's parameter but you've sent an instance of ImageService to it. It should be like this:
pictureBox1.LoadAsync(_imageService.GetImage(a string parameter for name));

Utillize string filename from form1 to form 2

In form 1 I have open an xml file. Now I want to able to use the string filename in Form2 so I am able to do extra feature and/or use what inside the file.
Form1
DialogResult result;
string filename;
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
fileChooser.Filter = "Xml Files (*.xml)|*.xml";
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
filename = fileChooser.FileName;
}
}
Form2
namespace PreviewForm
{
public partial class Preview : Form
{
int ind1 = 1;
public Preview()
{
InitializeComponent();
}
private void Preview_Load(object sender, EventArgs e)
{
//I want to able to do something like this
//XmlDocument xDoc = new XmlDocument();
//xDoc.Load(filename);
//foreach(XmlNode xNode in xdoc.SelectNode(People/People))
//{
// Label lable1 = new Label();
// label1.Text = xNode.SelectingSingleNode("Name").InnerText;
// label1.Name = "label_" + ind1;
// label1.Location = new Point(code);
// ind1++;
// this.Controls.Add(label1);
}
}
}
So I want to able to use the string filename in form1 to form2.
Just use a private field instance and add it to the constructor
namespace PreviewForm
{
private string _filename = string.Empty;
public partial class Preview : Form
{
int ind1 = 1;
public Preview(string filename)
{
InitializeComponent();
_filename = filename;
}
to use the string filename in Form2
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
fileChooser.Filter = "Xml Files (*.xml)|*.xml";
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
filename = fileChooser.FileName;
//for example here
PreviewForm form2=new PreviewForm(filepath);
form2.ShowDialog(this);
}
}
Solution 1 : You can send the FilePath from Form1 to the Form2 using constructor as below:
Form2 form2=new Fomr2(filepath);
form2.ShowDialog();
and create a string parameter constructor in Form2 as below:
string filepath;
public Preview(string filepath)
{
InitializeComponent();
this.filepath=filepath;
}
Solution 2: Make the filepath variable as public static in Form1 so that it can be accessible using its classname.
Try This:
public static string filepath;
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
fileChooser.Filter = "Xml Files (*.xml)|*.xml";
fileChooser.CheckFileExists = false;
result = fileChooser.ShowDialog();
filename = fileChooser.FileName;
Form2 form2=new Fomr2(filepath);
form2.ShowDialog();
}
}
From Form2 :
You can access from as below:
String filepath = Form1.filepath;
Some have already posted working examples, but I'd like to give you a general overview of what can be done when you need to pass data from a class to another one.
I'm presenting you with 3 basic ways to pass your data from the first class (the sender class) to the second (the receiver class):
Constructor Injection. This is what most people have described here, and it basically mean to have a "special" constructor on your receiver class that will be called from the sender class to pass the necessary data as a parameter when the receiver class object is instantiated. The data can then be saved to a local member on the receiver class.
Setter Injection. In this case, you define a public property on the receiver class that you call from the sender class, but after the receiver has been instantiated. As with the constructor injection, you can save the data to a local member on the receiver.
Method Injection. In this case, you define a method on the receiver class that will have a parameter defined to receive the data. here you can either decide to store the data to a member of the receiver, but you could also decide to use the data directly in the method body and discard it when done.
This is by no mean an exhaustive list of how you can pass data between classes, but it will give you a good starting point.
Cheers

How to populate a lstbox from a ,txt file at startup

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.

Categories