Textfiles with Forms and Multiple Outputs - c#

I have a code that needs to take input for the weather of certain day (and certain city) from the user and store that input into a textfile and then display that input for the specific cities from the textfile. I made use of FORMS.
How do I change my code to read the textfile correctly and NOT display each input 3 times each?
I added the relevant methods I made use of textfiles in:
private void btnCapture_Click(object sender, EventArgs e)
{
string city = cbCity.SelectedItem.ToString();
DateTime date = dtp.Value;
int minTemp = Convert.ToInt32(nudMinTemp.Value);
int maxTemp = Convert.ToInt32(nudMaxTemp.Value);
int precipitation = Convert.ToInt32(nudPrecip.Value);
int humidity = Convert.ToInt32(nudHumid.Value);
int windSpeed = Convert.ToInt32(nudWindSpeed.Value);
using (StreamWriter sw = new StreamWriter("myFile.txt"))
{
sw.WriteLine(city + Environment.NewLine + date +
maxTemp + Environment.NewLine + precipitation...);
sw.Close();
}
WeatherDetails w = new WeatherDetails(city, date, minTemp...)
w.ReadData();
MessageBox.Show("Your data has been Captured");
}
//Read data in WeatherDetails Class:
public void ReadData()
{
StreamReader SR = new StreamReader("myFile.txt");
while (!SR.EndOfStream)
{
city = SR.ReadLine();
date = DateTime.Parse(SR.ReadLine());
minTemp = int.Parse(SR.ReadLine());
maxTemp = int.Parse(SR.ReadLine());
precipitation = int.Parse(SR.ReadLine());
humidity = int.Parse(SR.ReadLine());
windSpeed = int.Parse(SR.ReadLine());
WeatherDetails newOne = new WeatherD...
ci.Add(newOne);
}
SR.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
city = cbCity.SelectedItem.ToString();
DateStart = dtpStart.Value;
DateEnd = dtpEnd.Value;
//Displaying data to RTB
private void btnDisplay_Click(object sender, EventArgs e)
{
city = cbCity.SelectedItem.ToString();
DateStart = dtpStart.Value;
DateEnd = dtpEnd.Value;
//Displaying data to RTB
foreach (WeatherDetails wd in WeatherDetails.ci)
{
rtbDisplay.Text += ("The Weather Report for " + cbCity.SelectedItem.ToString() + " , accesssed on " + wd.date.ToString() + "\n" +
"\n" +
"Maximum Temperature: " + wd.maxTemp + "\n" +
"Minimum Temperature: " + wd.minTemp + "\n" +
"Precipitation: " + wd.precipitation + "\n" +
"Humidity: " + wd.humidity + "\n" +
"Wind Speed: " + wd.windSpeed + "\n" +
"-------------------End OF Report---------------------");
The issue is that it is displaying the entered data 3 TIMES each.So if i enter data for one city on the 12th and the 14th of May, it will display the 12th 3 times and display the 14th 3 times.

Related

iText7 Align cut of a product description

I am trying to print a bill of sale, it works fine for me. But I have a problem, I don't know how to make the product description appear aligned, under the cut I make to print the rest of the description on a new line.
The full description is: "Aloe Vera Coco 12 x 1500 ml"
I leave the image and the code that prints the detail.
Someone who knows iText well and tell me how to solve this detail.
Thank you all
private void SetDetalles()
{
// 1 2 3 4 5
// 12345678901234567890123456789012345678901234567890
// "Cant Descripcion 000000000 000000000"
// --------------------------------------------------
SetLineaDivisora();
string linea = "Cant Descripcion Precio Total";
SetTextoNormal(linea);
SetLineaDivisora();
int maxLenLine = 25;
string descpart = "";
foreach (DetallesPDF det in detalles)
{
string descripcion = det.Descripcion;
if (maxLenLine > descripcion.Length)
{
descpart = descripcion.PadRight(25);
descripcion = "";
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
SetTextoNormal(linea);
}
else
{
bool lflag = true;
descpart = descripcion.Substring(0, maxLenLine);
do
{
if (lflag)
{
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
descripcion = descripcion.Substring(maxLenLine);
lflag = false;
}
else
{
descpart = descripcion.Substring(0);
linea = $" {descpart}"; // --> Add 5 blanks so it will be aligned, but the line break shows it on the left side.
descripcion = descripcion.Replace(descpart, "");
}
SetTextoNormal(linea);
}
while (descripcion.Trim().Length > 0);
}
}
SetLineaDivisora();
}
Function that generates the sale detail item
private void SetTextoNormal(string linea, float separacion = 0.2f, bool centrado = false)
{
Paragraph header = new Paragraph(linea)
//.SetTextAlignment(TextAlignment.LEFT)
.SetMultipliedLeading(separacion)
.SetFontSize(7)
.SetFont(currierNew);
if (centrado)
header.SetTextAlignment(TextAlignment.CENTER);
miDocumento.Add(header);
}

Data from List<Memo> doesn't show in datagridview

I have a list made by user input which is bound to a datasource class, I also have a datagridview where the data is supposed to be put into the datagrid.
private void ViewMemo_Load(object sender, EventArgs e)
{
dgvMemo.DataSource = Datasources.memorecorders;
}
this is the AddMemo class
private void btAdd_Click(object sender, EventArgs e)
{
int SerialId;
SerialId = int.Parse(txtSerialId.Text);
decimal price;
price = decimal.Parse(txtPrijs.Text);
MemoRecorder m1 = new MemoRecorder(SerialId);
m1.make = txtMerk.Text;
m1.model = txtModel.Text;
m1.priceExBtw = price;
m1.creationDate = dtProductie.Value;
foreach (MemoCartridgeType mem in Enum.GetValues(typeof(MemoCartridgeType)))
{
if (cbCartridge.SelectedValue.ToString() == mem.ToString())
{
m1.maxCartridgeType = mem;
}
}
Datasources.memorecorders.Add(m1);
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
txtMerk.Text = String.Empty;
txtModel.Text = String.Empty;
txtPrijs.Text = String.Empty;
}
but when I view the datagridview the data is not in there, what did I do wrong?
Datasources.memorecorders.Add(m1);
dgvMemo.DataSource = Datasources.memorecorders;
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);

The process cannot access the file "XXX.txt" because it is being used by another process

I would like to write to and read from the same text file. However, I faced the issue of "The process cannot access "XXX.txt" because it is being used by another process".
I created two classes, A & B and define two objects for each of the classes in the main form.
Class A will be writing data into the text file while Class B will reading data from the text file at the same time.
I had put Class B in a timer while Class A will start when I click a button.
Class A :-
private void Processdata(string indata)
{
//======================================[TCP/IP]=====================================================//
using (StreamWriter sw = new StreamWriter(TCPfilename, true))
{
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
sw.WriteLine(formattedTime + "\t" + indata);
}
// Regular Expression for WIFI Drone & Phantom 3 Drone
Regex regexp3_1 = new Regex(#"^AH(60601F740D70)(-\d{0,2})");
Regex regexp3_2 = new Regex(#"^AH(60601F415CAF)(-\d{0,2})");
Regex regexp3_3 = new Regex(#"^AH(60601F078D3E)(-\d{0,2})");
Regex regexp3 = new Regex(#"^AH(60601F(\S{0,6}))(-\d{0,2})");
Regex regexP3 = new Regex(#"^GGP3(\S{0,8})");
Regex regexPA = new Regex(#"^AH(A0143D\S{0,6})(-\d{0,2})");
Regex regex3D = new Regex(#"^AH(8ADC96\S{0,6})(-\d{0,2})");
Regex regexMA = new Regex(#"^AH(60601F93F3FB)(-\d{0,2})");
Regex regexMP = new Regex(#"^AH(60601F33729E)(-\d{0,2})");
Regex regexTL = new Regex(#"^AH(60601FD8A1EF)(-\d{0,2})");
// Regular Expression for WIFI
Regex regexAH = new Regex(#"^AH(\S{0,12})(-\d{0,2})");
Regex regexAH2 = new Regex(#"^AH(\S{0,12})(-\d{0,2})\S{0,6}(\S{0,74})");
// Match WIFI Drone & Phantom 3 Drone Data with Regular Expression
Match matchp3_1 = regexp3_1.Match(indata);
Match matchp3_2 = regexp3_2.Match(indata);
Match matchp3_3 = regexp3_3.Match(indata);
Match matchp3 = regexp3.Match(indata);
Match matchP3 = regexP3.Match(indata);
Match matchPA = regexPA.Match(indata);
Match match3D = regex3D.Match(indata);
Match matchMA = regexMA.Match(indata);
Match matchMP = regexMP.Match(indata);
Match matchTL = regexTL.Match(indata);
// Match WIFI Data with Regular Expression
Match matchAH = regexAH.Match(indata);
Match matchAH2 = regexAH2.Match(indata);
using (StreamWriter rssi = new StreamWriter(TCPRSSIfilename, true))
{
var time = DateTime.Now;
// Parrot
if (matchPA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Parrot" + "; " + matchPA.Groups[1].Value.ToString() + "; " + matchPA.Groups[0].Value.ToString() + "; " + matchPA.Groups[2].Value.ToString());
rssi.Flush();
}
// 3DR
else if (match3D.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-3DR_Solo" + "; " + match3D.Groups[1].Value.ToString() + "; " + match3D.Groups[0].Value.ToString() + "; " + match3D.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Air
else if (matchMA.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Air" + "; " + matchMA.Groups[1].Value.ToString() + "; " + matchMA.Groups[0].Value.ToString() + "; " + matchMA.Groups[2].Value.ToString());
rssi.Flush();
}
// Mavic Pro
else if (matchMP.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Mavic_Pro" + "; " + matchMP.Groups[1].Value.ToString() + "; " + matchMP.Groups[0].Value.ToString() + "; " + matchMP.Groups[2].Value.ToString());
rssi.Flush();
}
// Tello
else if (matchTL.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-Tello" + "; " + matchTL.Groups[1].Value.ToString() + "; " + matchTL.Groups[0].Value.ToString() + "; " + matchTL.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 740D70)
else if (matchp3_1.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_1.Groups[1].Value.ToString() + "; " + matchp3_1.Groups[0].Value.ToString() + "; " + matchp3_1.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 415CAF)
else if (matchp3_2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_2.Groups[1].Value.ToString() + "; " + matchp3_2.Groups[0].Value.ToString() + "; " + matchp3_2.Groups[2].Value.ToString());
rssi.Flush();
}
// Specific Phantom 3 (MAC : 078D3E)
else if (matchp3_3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3_3.Groups[1].Value.ToString() + "; " + matchp3_3.Groups[0].Value.ToString() + "; " + matchp3_3.Groups[2].Value.ToString());
rssi.Flush();
}
// General Phantom 3
else if (matchp3.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Drone-DJI_Phantom_3_STD" + "; " + matchp3.Groups[1].Value.ToString() + "; " + matchp3.Groups[0].Value.ToString() + "; " + matchp3.Groups[2].Value.ToString());
rssi.Flush();
}
// WIFI
else if (matchAH.Success && matchAH2.Success)
{
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
rssi.WriteLine(formattedTime + "; " + "Wifi -" + matchAH2.Groups[3].Value.ToString() + "; " + matchAH.Groups[1].Value.ToString() + "; " + matchAH.Groups[0].Value.ToString() + "; " + matchAH.Groups[2].Value.ToString());
rssi.Flush();
}
}
}
Class B :-
public void DisplayOnDataGridView(DataGridView dl, GMapControl gmap, string TCPRSSIfile, string UDPRSSIfile)
{
//================================[TCP/IP]==================================================//
using (StreamReader streamReader = new StreamReader(TCPRSSIfile, true))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+ -)(\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
var time = DateTime.Now;
string formattedTime = time.ToString("yyyy/MM/dd HH:mm:ss");
StringBuilder sb = new StringBuilder();
if (matchSearch.Groups[3].Value.ToString() != null)
{
for (int i = 0; i <= matchSearch.Groups[3].Value.ToString().Length - 2; i += 2)
{
//Convert Hex format to standard ASCII string
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(matchSearch.Groups[3].Value.ToString().Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
}
StringBuilder sbwifi = new StringBuilder(sb.Length);
foreach (char c in sb.ToString())
{
if ((int)c > 127) // 127 = Delete
continue;
if ((int)c < 32) // 1-31 = Control Character
continue;
if (c == ',')
continue;
if (c == '"')
continue;
sbwifi.Append(c);
}
Regex wifi = new Regex(#"^(\S+)\$");
Match matchwifi = wifi.Match(sbwifi.ToString());
if (matchwifi.Success)
{
sbwifi.Clear();
sbwifi.Append(matchwifi.Groups[1].Value.ToString());
}
if (matchSearch.Success)
{
try
{
if (dl.Rows.Count == 0)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
else
{
for (int row = 0; row < dl.Rows.Count; row++)
{
if (dl.Rows[row].Cells["DroneID"].Value.ToString() == matchSearch.Groups[4].Value.ToString())
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi") == false)
{
Image img1 = Image.FromFile(#"D:\Image\alert.PNG");
if (dl.Rows[row].Cells["DroneStatus"].Value != img1)
{
dl.Rows[row].Cells["DroneStatus"].Value = img1;
}
}
dl.Rows[row].Cells["TimeDetected"].Value = matchSearch.Groups[1].Value.ToString();
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
duplicate = true;
}
}
if (!duplicate)
{
if (matchSearch.Groups[2].Value.ToString().Contains("Wifi"))
{
using (StreamWriter rssi = new StreamWriter(#"D:\Skydroner\SearchReport.txt", true))
{
string DroneNameNoEmptySpace = matchSearch.Groups[2].Value.ToString().Replace(" ", String.Empty) + sbwifi.ToString().Replace(" ", String.Empty);
string DroneIDNoEmptySpace = matchSearch.Groups[4].Value.ToString().Replace(" ", String.Empty);
rssi.WriteLine(formattedTime + " " + DroneNameNoEmptySpace + " " + DroneIDNoEmptySpace + " Detected");
}
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString() + " " + sbwifi.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
//DetectedZone(gmap, false);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
else
{
string[] newlist = new string[] { matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[4].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
//DetectedZone(gmap, true);
Image img = Image.FromFile(#"D:\Image\no_status.PNG");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
RSSI_Signal(dl, matchSearch.Groups[6].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
//========================================[UDP]===================================================//
using (StreamReader streamReader = new StreamReader(UDPRSSIfile))
{
string line = String.Empty;
while ((line = streamReader.ReadLine()) != null)
{
Regex Search = new Regex(#"^(\S+ \S+); (\S+); (\S+); (\S+); (\S+)");
Match matchSearch = Search.Match(line);
if (matchSearch.Success)
{
try
{
//if (matchSearch.Groups[4].Value.ToString() != "0.000000")
//{
string[] newlist = new string[] { matchSearch.Groups[2].Value.ToString(), matchSearch.Groups[3].Value.ToString(), matchSearch.Groups[1].Value.ToString(), "Add", "Distract", "", "" };
dl.Rows.Add(newlist);
//}
dl.Rows[rownumber].Cells["Whitelist"].Style.BackColor = Color.LightGray;
if (dl.Rows[rownumber].Cells["DroneType"].Value.ToString().Contains("Wifi"))
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.DarkGray;
DetectedZone(gmap, false);
}
else
{
dl.Rows[rownumber].Cells["Inject"].Style.BackColor = Color.LightGreen;
DetectedZone(gmap, true);
}
Image img = Image.FromFile(#"D:\Image\arrow.jpg");
dl.Rows[rownumber].Cells["DroneStatus"].Value = img;
RSSI_Signal(dl, matchSearch.Groups[5].Value.ToString(), rownumber);
rownumber = rownumber + 1;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
else
{
// Do Nothing
}
}
}
// Add Number for Each DataGridView Row
if (null != dl)
{
foreach (DataGridViewRow r in dl.Rows)
{
dl.Rows[r.Index].HeaderCell.Value = (r.Index + 1).ToString();
}
}
}
Main Form :-
//========Call Class A Object==============//
private void button2_Click(object sender, EventArgs e)
{
// TCP/IP Address - Debug TCP Text File - Debug UDP Text File - UDP Port Number - TCP/IP RSSI Text File - UDP RSSI Text File
ListeningPole lp1 = new ListeningPole();
lp1.PortConnect("192.168.1.133", #"D:\Skydroner\SkyDroner_DebugTCP_1.txt", #"D:\Skydroner\SkyDroner_DebugUDP_1.txt", 61557, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
//========Timer to Run Class B Object==============//
private void MainForm_Load(object sender, EventArgs e)
{
// Start Timer for Display Scroll Mouse Message
RowCountTimer.Interval = 1000;
RowCountTimer.Start();
}
private void RowCountTimer_Tick(object sender, EventArgs e)
{
Display dp1 = new Display();
dp1.DisplayOnDataGridView(DroneList, gmap, #"D:\Skydroner\SkyDroner_TCP_RSSI_1.txt", #"D:\Skydroner\SkyDroner_UDP_RSSI_1.txt");
}
Anyone have any solution for this error.
Please help.
Thanks.
Make sure to call Close() on the writer to close it before reading. I've seen instances where utilizing a using block with the writer may not close it in time for the reader to be able to read it.

How to get specific character in listbox

I have a listbox in which my selected products are stored like this ...
'Product name'.padright(30) 'price' 'quantity'
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
but when I read price of a product it selects price and quantity
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
I only want price in currentPriceString and quantity in quantityString
here is complete code of this method
private void ProductButton_Click(object sender, EventArgs e)
{
Button ProductButton = sender as Button;
DataAccess dataAccess = new DataAccess();
int ProductID = Convert.ToInt32(ProductButton.Tag);
Details details = dataAccess.ReadProductDetails(ProductID);
decimal price = details.Price;
string foundItem = CheckProductInListBox(details.Name);
if (!String.IsNullOrEmpty(foundItem))
{
string currentPriceString = foundItem.Replace(details.Name.PadRight(30), "");
decimal currentPriceValue;
string quantityString = foundItem.Replace(details.Name.PadRight(33), "");
int quantiy;
MessageBox.Show(currentPriceString);
if (Decimal.TryParse(currentPriceString, out currentPriceValue))
{
quantiy = Convert.ToInt16(quantityString);
currentPriceValue += price;
quantiy++;
string newItem = details.Name.PadRight(30) + currentPriceValue.ToString() + quantiy.ToString();
int index = listBox1.Items.IndexOf(foundItem);
listBox1.Items[index] = newItem;
}
else
{
MessageBox.Show("Error");
}
}
else
{
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
}
}
private string CheckProductInListBox(string name)
{
foreach (string item in listBox1.Items)
{
if (item.Contains(name))
{
return item;
}
}
return String.Empty;
}
On replacing (foundItem.Replace(details.Name.PadRight(33), "");), you are just removing the name part from the string, so the price and quantity will be there for sure.
You should can try this code,
// suppose your found text is like this,
//foundItem = "AMIT".PadRight(30) + "200" + " " + "1";
You can get price and quantity separately like below:
string currentPriceQuantityString = foundItem.Replace(details.Name.PadRight(30), "");
//currentPriceQuantityString => "200 1"
string[] strArray = currentPriceQuantityString.Split();
string currentPriceString = strArray[0]; //currentPriceString => "200"
string quantityString = strArray[1]; //quantityString => "1"
Side note:
I guess your line:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + 1 );
..should be:
listBox1.Items.Add(details.Name.PadRight(30) + details.Price.ToString() + " " + "1" );

Setting a string from one destination to another

I want to include the string "oldSummary" in the second richtextbox, however all of the summary's functionality belongs to a streamRead after opening a file. Is there a way for that when btn1 button is clicked, it will display the oldSummary string? At the moment it's blank due to it's global string set to "" but I want it to display the oldSummary string set in the mnuOpen button.
string oldSummary = "";
private void mnuOpen_Click(object sender, EventArgs e)
{
//Load up file code which I remove for this example but goes hereā€¦
//Add data from text file to rich text box
richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);
//Read lines of text in text file
string textLine = "";
int lineCount = 0;
System.IO.StreamReader txtReader;
txtReader = new System.IO.StreamReader(Chosen_File);
do
{
textLine = textLine + txtReader.ReadLine() + " ";
lineCount++;
}
//Read line until there is no more characters
while (txtReader.Peek() != -1);
//seperate certain characters in order to find words
char[] seperator = (" " + nl).ToCharArray();
//number of words, characters and include extra line breaks variable
int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;
int numberOfChar = textLine.Length - lineCount;
string divider = "------------------------";
//Unprocessed Summary
string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
txtReader.Close();
}
private void btn1_Click(object sender, EventArgs e)
{
string wholeText = "";
string copyText = richTextBox1.Text;
wholeText = oldSummary + copyText;
richTextBox2.Text = wholeText;
}
If you want to use the global variable oldSummary then do not redeclare one with the same name inside the menu open event handler, just use the global one
//Unprocessed Summary
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
Try replacing:
string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
with:
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;
so that you assign the value to the class field used in btn1_Click.

Categories

Resources