I have code like this:
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string ext = Path.GetExtension(openFileDialog1.FileName);
if(string.Compare(ext, ".FDB") == 0)
{
string fileName = openFileDialog1.SafeFileName;
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName);
string databaseTxt = #"C:\Users\arist\AppData\Roaming\TDWork\";
string[] database = { fileDirectory + fileName };
if (Directory.Exists(databaseTxt))
{
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(databaseTxt);
System.IO.File.WriteAllLines(databaseTxt + "databases.txt", database);
}
}
else
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
e.Cancel = true;
}
}
Now, i want to create more buttons that open same file dialog. Problem is that i want to pass openFileDialog directory to different textboxes. So logic is this:
If i open with button1, pass value to textbox1,
If i open with button2, pass value to textbox2,
if i open with button3, pass value to textbox3.
So i wanted to create int check (1, 2, 3) so when i press button1, it pass check = 1 to OpenDialog1_FileOk, so i just do switch there and do actions.
Problem is i do not know how to pass it to handler, and if that is possible. Also if there is any other solution, please write it.
First, you could use your openfiledialog just like this, without handling a whole new function for it:
if(openFileDialog1.ShowDialog() == DialogResult.OK){
//...code
}
Second, for your goal you'll have to be sure that the names of your controls are exactly ending on the digit you want (e.g. "button1" and "textbox1"). Then you can do it like this:
void Button1Click(object sender, EventArgs e)
{
//MessageBox.Show(bt.Name[bt.Name.Length - 1].ToString());
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
if(!Path.GetExtension(openFileDialog1.FileName).EndsWith(".FDB")) //checking if the extension is .FDB (as you've shown in your example)
{
MessageBox.Show("Fajl koji ste izabrali nije Firebird baza (.FDB)");
return; //return if it's not and no further code gets executed
}
string fileDirectory = Path.GetDirectoryName(openFileDialog1.FileName); //getting the directory
string nameOfMyButton = (sender as Button).Name; //you get the name of your button
int lastDigitOfMyName = Convert.ToInt16(Name[Name.Length - 1]); //returns the number of your button
TextBox neededTextboxToShowDirectory = this.Controls.Find("textbox" + lastDigitOfMyName, true).FirstOrDefault() as TextBox; //this will search for a control with the name "textbox1"
neededTextboxToShowDirectory.Text = fileDirectory; //you display the text
//... doing the rest of your stuff here
}
}
You could use a private field where you save temporarily the text of your TextBox and deploy it in the click event like this:
private int whichButton = 0;
private void button1_Click(object sender, EventArgs e)
{
whichButton = 1;
openFileDialog1.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
whichButton = 2;
openFileDialog1.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
whichButton = 3;
openFileDialog1.ShowDialog();
}
use then the whichButton to choose
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
switch (whichButton)
{
....
}
}
Related
Now solved. Thanks for your answers!
This is my code right now:
//Listbox scripts is the name of my folder
private void Form1_Load(object sender, EventArgs e)
{
foreach (var file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + #"Listbox scripts"))
{
string file2 = file.Split('\\').Last();
listBox1.Items.Add(file2);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
webBrowser1.Document.InvokeScript("SetText", new object[]
{
File.ReadAllText(string.Format("./Listbox scripts/{0}", listBox1.SelectedItem.ToString()))
});
}
I'm new to coding in C# and I have a textbox that has the names of text files in a directory and when I click on the text file in the listbox it's supposed to load the text from it into my textbox (named 'ScriptBox')
Here's my code:
private void Form1_Load(object sender, EventArgs e)
{
string User = System.Environment.MachineName;
textBox1.Text = "{CONSOLE} Welcome to Linst, " + User + "!";
directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + #"Scripts");
files = directory.GetFiles("*.txt");
foreach (FileInfo file in files)
{
listBox1.Items.Add(file.Name);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var selectedFile = files[listBox1.SelectedIndex];
ScriptBox.Text = File.ReadAllText(selectedFile.FullName); //these parts are the parts that dont work
}
Thanks in advance!
Add the below into your Form1.cs. What this is going to do is when a user clicks a listbox item, its going to call (raise an event) the "listBox1_MouseClick" method and set the text of the textbox to the text of the listbox item. I just quickly created an app and implemented the below and it works.
private void listBox1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Text = listBox1.Text;
}
And add the below to the Form1.Designer.cs where the rest of your list box properties are. The below is subscribing to an event, the listBox1_MouseClick method in Form1.cs, so when a user clicks on a listbox item, the listBox1_MouseClick method is going to run.
this.listBox1.MouseClick += new MouseEventHandler(this.listBox1_MouseClick);
I hope the above makes sense.
Your code is nice, and perfect but it just need a little validation check in list index selection
Try thing in your listbox_selectedIndexChanged
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex!=-1)
{
FileInfo selectedFile = files[listBox1.SelectedIndex];
ScriptBox.Text = File.ReadAllText(selectedFile.FullName);
}
}
I actually don't see a problem with your code, could it be a typo somewhere?
I did this and it worked for me:
private void Form1_Load(object sender, EventArgs e)
{
foreach (var file in System.IO.Directory.GetFiles(#"c:\"))
{
listBox1.Items.Add(file);
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
textBox1.Text = System.IO.File.ReadAllText(listBox1.SelectedItem.ToString());
}
}
I am trying to make a program for the car retail firm I work at. When people deliver their cars, a guy has to take pictures of the damages with a Lenovo miix.
The program I've made so far is not smart enough.
It goes like, you write the numberplate in a box, then create a folder with the text from the box.
Then you start the camera, take a picture and save it, and manually have to find the folder and name the file.
Is there a way I can make it smarter with just 2 buttons, one to start the camera and another one to take the picture, and then it automatically saves it in a folder named as the numberplate, and files named 1,2,3,4 and so on.jpg ?
this is my code so far:
namespace Europcar_skade_camera
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection webcam;
private VideoCaptureDevice cam;
private void Form1_Load(object sender, EventArgs e)
{
webcam = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach(FilterInfo VideoCaptureDevice in webcam)
{
comboBox1.Items.Add(VideoCaptureDevice.Name);
}
comboBox1.SelectedIndex = 1;
}
private void button1_Click(object sender, EventArgs e)
{
cam = new VideoCaptureDevice(webcam[comboBox1.SelectedIndex].MonikerString);
cam.NewFrame += new NewFrameEventHandler(Cam_NewFrame);
cam.Start();
}
private void Cam_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bit = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = bit;
}
private void button3_Click(object sender, EventArgs e)
{
if (cam.IsRunning)
{
cam.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDialog1.InitialDirectory = #"C:\tmp\";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image.Save(saveFileDialog1.FileName);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void nummerplade_TextChanged(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(#"c:\tmp\" + nummerplade.Text);
}
}
}
Something like this:
Instead of using a SaveFileDialog, you could just create the file path based on the number plate value like this:
var filePath = System.IO.Path.Combine(#"c:\tmp", nummerplade.Text, fileNumber + ".jpeg");
The fileNumber var is the number of files allready in the folder + 1.
var fileNumber = Directory.GetFiles(...).Length + 1
string numberPlate = "21323412";
string path = #"C:\tmp\";
Directory.CreateDirectory(path + numberPlate); //to create folder
string dirpath = path + numberPlate; //to get name of fodler we created
You also mentioned that you want incremental names, there are many ways of doing it, personally i'd prefer large hashed name of file like so:
//generate GUID and convert to string.
string filename = Guid.NewGuid().ToString();
//to save picturebox image in folder and use ImageFormat.Your desired format
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg);
But if you want to stick with incremental names:
// you get last name in the folder:
//it gets last filename in folder but with path
var lastFilePath = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();
//we remove path from filename and convert it to int.
int lastIndex = Int32.Parse(Path.GetFileNameWithoutExtension(lastFilePath));
//then we increment it by 1
int newName = lastIndex + 1;
//and save it
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg); //to save picturebox image in folder
With GUID finally it should look something like this:
string numberPlate = "21323412";
string path = #"C:\tmp\";
private void button2_Click(object sender, EventArgs e)
{
Directory.CreateDirectory(path + numberPlate); //to create folder
string dirpath = path + numberPlate; //to get name of fodler we created
string filename = Guid.NewGuid().ToString();
pictureBox1.Image.Save(dirpath + #"\"+filename+".jpeg", ImageFormat.Jpeg); //to save picturebox image in folder
}
I've a gui and I get temperature data from a Uc. I can see the data in the rich text box and save to a text file. But I cannot understand how to sort the saved data in the column format. Right now it is a long row of data. Please advice.
Would it be advisable to replace the rich text box to a normal text box?
I've a button to save data to the text file (button3_Click);
using System;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
namespace Serial_receive
{
public partial class Form1 : Form
{
// All members variables should be placed here
// make it more readable, hopefully!
string t;
SerialPort sp;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
// User can already search for ports when the constructor of the FORM1 is calling
// And let the user search ports again with a click
// Searching for ports function
SearchPorts();
}
//search button
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
SearchPorts();
}
void SearchPorts()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
private void button2_Click(object sender, EventArgs e)
{
// Catch exception if it will be thrown so the user will see it in a message box
OpenCloseSerial();
}
void OpenCloseSerial()
{
try
{
if (sp == null || sp.IsOpen == false)
{
t = comboBox1.Text.ToString();
sErial(t);
button2.Text = "Close Serial port"; // button text
}
else
{
sp.Close();
button2.Text = "Connect and wait for inputs"; // button text
}
}
catch (Exception err) // catching error message
{
MessageBox.Show(err.Message); // displaying error message
}
}
void sErial(string Port_name)
{
try
{
sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One); // serial port parameters
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
sp.Open();
}
catch (Exception err)
{
throw (new SystemException(err.Message));
}
}
//
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
// This below line is not need , sp is global (belongs to the class!!)
//SerialPort sp = (SerialPort)sender;
if (e.EventType == SerialData.Chars)
{
if (sp.IsOpen)
{
string w = sp.ReadExisting();
if (w != String.Empty)
{
Invoke(new Action(() => richTextBox1.AppendText(w)));
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sp == null || sp.IsOpen == false)
{
OpenCloseSerial();
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Serial Channel to FRDM-KW40Z";
}
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\Users\varman\Documents\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string temperature = "Temperature";
string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
sorted = sorted.Substring(sorted.IndexOf(temperature));
File.WriteAllText(saveFileDialog1.FileName, sorted);
Text += "\r\n";
richTextBox1.Text = saveFileDialog1.FileName;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
richTextBox1.ScrollBars = ScrollBars.Both;
}
}
}
I assume you want to sort it only in the output file because you didn't share the code that change richTextBox1.Text.
So you can add a new line for each temperature before writing to the file:
private void button3_Click(object sender, EventArgs e)
{
...
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string temperature = "Temperature";
string sorted = richTextBox1.Text.Replace(temperature, Environment.NewLine + temperature);
File.WriteAllText(saveFileDialog1.FileName, sorted);
Text += "\r\n";
richTextBox1.Text = saveFileDialog1.FileName;
}
}
Add this line of code before File.WriteAllText if you want to write the text that starts with "Temperature" (this way you remove the "?????" at the beginning):
sorted = sorted.Substring(sorted.IndexOf(temperature));
EDIT:
Following your last edit - you added the code that updates the RichTextBox. So you can do the sorting by column only in DataReceivedHandler. See below:
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
if (e.EventType != SerialData.Chars || !sp.IsOpen)
{
return;
}
string w = sp.ReadExisting();
if (w != String.Empty)
{
string temperature = "Temperature";
string sorted = w.Replace(temperature, Environment.NewLine + temperature);
Invoke(new Action(() => richTextBox1.AppendText(sorted)));
}
}
Basically what you need to understand is that File.WriteAllText(fileName, input) is where you write input into the file, so you can manipulate input as you wish before that line. If you wish to alter the text before it's dispalyed in the RichTextBox then you need to see where you execute something like richTextBox1.AppendText(input) or richTextBox1.Text = input and do all the changes you want on input before that line.
I have a windows form that reads strings from a file and shows them all in a textbox when I press a button.
private void buttonTxt_Click(object sender, EventArgs e)
{
string[] Test = File.ReadAllLines("C:\\testfile.txt");
for (int i = 0; i < testfile.Length; i++)
{
TextBox.Text += testfile[i];
}
}
I'd like to make two radio buttons. So that first button lets my program work the way I described (by default) AND second radio button makes it work vice versa -- so that I could write in a textbox myself and when I press a button it writes a new line to the same file. Is there a way to do it?
Simply add an if statement in this event handler and implement both sending and receiving the data. Done. Sample in principle:
private const string FilePath = #"C:\testfile.txt";
private void buttonTxt_Click(object sender, EventArgs e)
{
if (radioReadMode.Checked) // check which radio button is selected
{ // read mode
string[] Test = File.ReadAllLines(FilePath);
for (int i = 0; i < testfile.Length; i++)
TextBox.Text += testfile[i];
}
else
{ // write mode
File.WriteAllText(FilePath, TextBox.Text);
}
}
I believe this is what you might be looking for. If radio button 1 is checked then if the file exists it will read that file and put it into a textbox in the form. If you switch to radio button 2. You can type in the text box and then when you press the button it will append it to the file.
public partial class Form1 : Form
{
System.IO.StreamReader sr;
System.IO.StreamWriter sw;
public Form1()
{
InitializeComponent();
radioButton1.Checked = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sr = new System.IO.StreamReader("C:\\testfile.txt");
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + "\r\n";
}
}
finally
{
sr.Close();
sr.Dispose();
}
}
}
if (radioButton2.Checked == true)
{
if (System.IO.File.Exists("C:\\testfile.txt"))
{
try
{
sw = new System.IO.StreamWriter("C:\\testfile.txt", true);
string result = textBox1.Text;
string[] lststr = result.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in lststr)
{
sw.WriteLine(s);
}
}
finally
{
sw.Flush();
sw.Close();
sw.Dispose();
}
}
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
textBox1.Clear();
textBox1.ReadOnly = false;
}
}
Yes, there's a way. Just add another button to your form and inside read the text from the text box this way:
var textBoxContent = TextBox.Text;
and save it to your file this way
File.WriteAllText("C:\\testfile.txt", textBoxContent);
Note: I recommend getting the path to your file into a variable
I've started to learn about System.IO in C# and I want to achieve something like this:
I have two buttons and one TextBox.
The first button event is supposed to use FolderBrowserDialog and let me choose a specific a folder.Then, to save its path in a variable.
The text box is supposed to get as a value the number of folders that I want to create in the choosen path.
The second button is going to create the number of folders(with different name each) written in the textbox at the first button specified path.
My buttons and textbox events so far:
...
int value;
String path;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
path = folderBrowserDialog1.SelectedPath;//store selected path to variable "path"
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (!Directory.Exists(path))//if selected path exists
{
for(int i=0;i<value;i++)//trying to go through as folders as I wrote in the TextBox
{
Directory.CreateDirectory(path + "something");//is something wrong here, I guess.
}
}
}
My questions so far:
what's wrong with my code ?
how can I create each time the for(){} executes a folder with different name ?
I would appreciate any help
int value;
string path = null;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog(this) == DialogResult.OK)
{
MessageBox.Show(fbd.SelectedPath);
path = fbd.SelectedPath; //fbd not folderBrowserDialog1
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
value = Convert.ToInt32(textBox1.Text);//store the value from the textbox in variable "value"
}
private void button2_Click(object sender, EventArgs e)
{
if (path != null && Directory.Exists(path))
for(int i=0;i<value;i++)
Directory.CreateDirectory(Path.Combine(path,string.Format("SomeFolder{0}",i)));
}