Random Sentence Generator / Listbox output - c#

I am trying to make a windows form in C# that will have four arrays with 5 random words in them. I will then create a button to generate a random sentence using the words from the array. Right now I am trying to output the sentences to a list box but I am getting errors. What is the code to output this information to a listbox? Here is my 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 Chapter_16_Ex._16._4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnGenerator_Click(object sender, EventArgs e)
{
string[] article = { "the", "a", "one", "some", "any", };
string[] noun = { "boy", "girl", "dog", "town", "car", };
string[] verb = { "drove", "jumped", "ran", "walked", "skipped", };
string[] preposition = { "to", "from", "over", "under", "on", };
Random rndarticle = new Random();
Random rndnoun = new Random();
Random rndverb = new Random();
Random rndpreposition = new Random();
int randomarticle = rndarticle.Next(article.Length);
int randomnoun = rndnoun.Next(noun.Length);
int randomverb = rndverb.Next(verb.Length);
int randompreposition = rndpreposition.Next(preposition.Length);
listBox1.Items.Add("{0} {1}",article[randomarticle],noun[randomnoun]);
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}

Listbox.Items.Add
does not take 3 parameters
you will need to use String.Format when you use '{0} {1}' and you want to add values to that
listBox1.Items.Add(String.Format("{0} {1}", article[randomarticle], noun[randomnoun]));
or you could also just do it like this:
listBox1.Items.Add(article[randomarticle] + " " + noun[randomnoun]);
if i do it like that, it works perfect.

You can add string values to listbox control. So you should add your sentence like this:
listBox1.Items.Add(String.Format("{0} {1}", article[randomarticle], noun[randomnoun]));

Related

The process cannot access the file because it is being used by another process Streamwriter

I am getting an error that my textfile that is used to create and save my dictionary is being used by another process, I have used Process explorer to no result on what could be using my file. Below is my code and the code throwing this error.
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 meade_9_10
{
public partial class Form1 : Form
{
private Dictionary<string, string> names = new Dictionary<string, string>()
{
};
public Form1()
{
//Make sure Form1 is loaded and ran on program open
InitializeComponent();
this.Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
//Grab myfile.txt and convert to array
StreamReader sr = new StreamReader("myfile.txt");
string line;
while ((line = sr.ReadLine()) != null)
{
string[] arr = line.Split(',');
int i = 0;
//Add array objects to names dictionary
while (i < arr.Length)
{
names[arr[i]] = arr[i + 1];
i += 2;
}
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
//declare variables
string nameAdd;
string emailAdd;
//Put user input into variable
nameAdd = txtNameAdd.Text;
emailAdd = txtEmailAdd.Text;
//Declare new dictionary key pair as user input
names[emailAdd] = nameAdd;
//clear the textbox controls
txtNameAdd.Text = "";
txtEmailAdd.Text = "";
}
private void btnDelete_Click(object sender, EventArgs e)
{
string emailDel;
emailDel = txtEmailDel.Text;
//Remove key pair that is inputted by user
names.Remove(emailDel);
}
private void btnChange_Click(object sender, EventArgs e)
{
//Declare variables
string emailDel;
string nameAdd;
string emailAdd;
//Assign values to variables
emailDel = txtEmailChange.Text;
nameAdd = txtNameNew.Text;
emailAdd = txtEmailNew.Text;
//Delete the user inputted email to change
names.Remove(emailDel);
//Add the new key pair values to dictionary
names.Add(emailAdd, nameAdd);
}
private void btnLookUp_Click(object sender, EventArgs e)
{
//Declare variable
string email = txtEmail.Text;
//If statement to check if dictionary contains key value
if (names.ContainsKey(email))
{
outputName.Text = names[email];
outputEmail.Text = email;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
//writes the names dictioanry to array inside text file
File.WriteAllLines("myfile.txt",
names.Select(x => x.Key + "," + x.Value ).ToArray());
//Closes the program
this.Close();
}
}
}
The part of my code giving me the error
System.IO.IOException: 'The process cannot access the file 'C:\Users\Adrian\Desktop\ALL SCHOOL FILES\Fall 2021\C#\meade_9_10\bin\Debug\myfile.txt' because it is being used by another process.'
is
names.Select(x => x.Key + "," + x.Value ).ToArray());
I just cannot figure out what process is using my text file that is breaking this program, it was working earlier and I haven't made any changes except for removing redundant white space between functions.
Try using the
StreamReader.Close() method after your innermost while loop:
Closes the StreamReader object and the underlying stream, and releases any system resources associated with the reader.
Alternatively, you can use the using statement:
Provides a convenient syntax that ensures the correct use of IDisposable objects.

Control X accessed from a thread other than the thread it was created on

I use OPC-UA SDK of treager. I have variable created be PLC S7-1200
.
It displayed the value on Console.WriteLine, but I cant show it on listView
.
Can someone help me show the variable changes on listView1 ?
If I note listView1.Items.Add(itm); It will show that
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Opc.Ua.Client;
using Opc.UaFx;
using Opc.UaFx.Client;
namespace Test_OPC
{
public partial class OPCUA : Form
{
private readonly OpcClient client;
public static OpcValue isRunning;
string[] arr = new string[4];
ListViewItem itm;
public OPCUA()
: base()
{
this.client = new OpcClient("opc.tcp://192.168.1.200:4840");
InitializeComponent();
}
private void OPCUA_Load(object sender, EventArgs e)
{
client.Connect();
OpcSubscription subscription = client.SubscribeDataChange("ns=4;i=15",HandleDataChanged);
//ListViewItem listView1 = new ListViewItem();
//ListViewItem itemHienThi = new ListViewItem();
//Add Item vào ListView
arr[0] = "01";
arr[1] = "100";
arr[2] = "10";
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
}
private void HandleDataChanged(object sender,OpcDataChangeReceivedEventArgs e)
{
OpcMonitoredItem item = (OpcMonitoredItem)sender;
//Add the attribute name/value to the list view.
arr[0] = item.NodeId.ToString();
arr[1] = e.Item.Value.ToString();
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
Console.WriteLine("Data Change from NodeId '{0}': {1}",item.NodeId,e.Item.Value);
}
}
}

Directory with pdf-file rename with array c#

I’m stuck renaming files.
I have a directory with pdf-files and I want to rename them automatically.
I read a CSV-file and show it in a datagrid with C#.
First column is the old filename and second is the new filename.
The old filenames have numbers before .pdf
The new filenames have numbers, letters and equel signes in the names before .pdf
I tired several code examples but the don't work for me. I’m a newbe. Below the code for creating the datagrid (array). How do I use the rows of the array to search fort he old name and rename it with the new name?
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 VerplaatsenEnHernoemen
{
public partial class Form1 : Form
{
DataGridView my_datagridview = new DataGridView();
DataTable my_datatable = new DataTable();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Size = new Size(750, 500);
my_datagridview.Size = new Size(600, 400);
my_datagridview.Location = new Point(5, 5);
string[] raw_text = System.IO.File.ReadAllLines("D:\\names.csv");
string[] data_col = null;
int x = 0;
foreach (string text_line in raw_text)
{
data_col = text_line.Split(';');
if (x == 0)
{
for (int i =0;i<=data_col.Count() -1; i++)
{
my_datatable.Columns.Add(data_col[i]);
}
x++;
}
else
{
my_datatable.Rows.Add(data_col);
}
}
my_datagridview.DataSource = my_datatable;
this.Controls.Add(my_datagridview);
}
}
}

Making dynamic check boxes perform and action c#

I'm working on making a program give the ability to allow the user to set a target of an active window.
I have two problems with my code, perhaps someone can let me know if the path i've chosen is wrong or there is a better path.
The Window output is only showing 16 characters of the name of the process.
I have the check box listed but don't know how to dynamically assign them to do the change where it will make the TextBox.Text Change.
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;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace Workspace
{
public partial class Form5 : Form
{
string target = File.ReadAllText("./target.txt");
public Form5()
{
InitializeComponent();
//Shows current target in textbox.
string target = File.ReadAllText("./target.txt");
textBox1.Text = target;
// Sets a starting point.
int total_processes = 0;
// Captures proccesses.
Process[] processlist = Process.GetProcesses();
//looks at all proccess to separate with titles.
foreach (Process process in processlist)
{
//calculates total proccess with titles.
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
total_processes = total_processes + 1;
}
}
// Sets up string array total by number of processes with name.
string[] stringArray = new string[total_processes];
//Names each proccess array.
int loopnum = 0;
foreach (Process process in processlist)
{
if (!String.IsNullOrEmpty(process.MainWindowTitle))
{
stringArray[loopnum] = process.MainWindowTitle;
loopnum = loopnum + 1;
}
}
// Generates # of Radio buttons per proccess with name.
System.Windows.Forms.RadioButton [] radioButtons = new System.Windows.Forms.RadioButton[total_processes];
for (int i = 0; i < total_processes; ++i)
{
radioButtons[i] = new RadioButton();
radioButtons[i].Text = stringArray[i];
radioButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);
radioButtons[i].CheckedChanged += new EventHandler(this.radioButtons_CheckChanged);
this.Controls.Add(radioButtons[i]);
}
}
private void radioButtons_CheckChanged(object sender, EventArgs e)
{
// Dynamic Check box if checked changes textBox1.Text to radioButtons[i].Text
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.StreamWriter file = new System.IO.StreamWriter("./target.txt");
file.WriteLine(textBox1.Text);
file.Close();
}
}
}
Use ((System.Windows.Forms.RadioButton)sender).Text to get the text property of your radio button:
private void radioButtons_CheckChanged(object sender, EventArgs e)
{
textBox1.Text= ((System.Windows.Forms.RadioButton)sender).Text;
}
When an event raises, the sender cotains a reference to your control that raised the event, so you can access properties of sender control.

How to write text of a same file to multiple text files in c#

I have a text file of 11 bytes now i want to split and write the text to multiple files say 2 bytes for each file and 3 for the last file how to do this using c#
For now here is my code which writes the whole file to a new 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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.Text = textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
var fileName = Text;
FileInfo fi = new FileInfo(fileName);
var size = fi.Length;
int i = Convert.ToInt32(size);
int j = Convert.ToInt32(comboBox1.SelectedItem);
decimal ireminder = (decimal)i % j;
MessageBox.Show(ireminder.ToString());
StreamReader sr = new StreamReader(Text);
var line = sr.ReadLine();
StreamWriter sw = new StreamWriter("D:\\Test.txt");
sw.WriteLine(line);
sw.Close();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}

Categories

Resources