visual studio C# listview save and load problem - c#

i have a problem with visual studio c# listview items that i cant found a solution over googling.
I've made from application with a listview, i can add, remove, update listview items.
I'm saving and loading the listview to/from file correctly with this code:
private void saveListViewItems(string path, ListView lv)
{
var delimeteredListviewData = new List<string>();
string delimeteredItems = string.Empty;
foreach (ListViewItem lvi in lv.Items)
{
foreach (ListViewItem.ListViewSubItem lvsi in lvi.SubItems)
{
delimeteredItems += lvsi.Text + "#";
}
delimeteredListviewData.Add(delimeteredItems);
}
System.IO.File.WriteAllLines(path, delimeteredListviewData.ToArray());
}
private void loadListViewItems(string path, ListView lv)
{
foreach (string line in System.IO.File.ReadAllLines(path))
{
lv.Items.Add(new ListViewItem(line.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries)));
}
}
the problems is i have activated checkbox next to each item. i cant save listview items with checkbox checked. i want to save listview and load with selected items. thanks

Something like this?:
List<string> delimeteredItems = new List<string>();
foreach (ListViewItem lvi in listView1.CheckedItems)
{
string item= String.Join("#", lvi.SubItems.Cast<ListViewItem.ListViewSubItem>().Select(si=>si.Text));
delimeteredItems.Add(item);
}
System.IO.File.WriteAllLines(#"c:\temp\lines.txt", delimeteredItems);

Instead of only saving the string you need to save more information.
You can added add a IsChecked value together with your string.
You need a small wrapper class that holds both values as a property.
Then you can use serilization, it is a term to describe a way to convert an object to something you can store on disk.
There are many formats to pick from, but Json is a good readable format. You can download the Nuget package NewtonSoft.Json via the nuget package manager.
public class StoreListView
{
public void StoreToDisk(string path, List<ItemDataHolder> list)
{
string theListInJsonFormat = JsonConvert.SerializeObject(list);
File.WriteAllText(path, theListInJsonFormat);
}
}
public class ItemDataHolder
{
public string SomeValuesYouWantToSave { get; set; }
public bool IsChecked { get; set; }
}

I've Managed the program to work.
I was wrong about the way reading/writing the text file.
now I'm using ini-parser nuget.
installed ini parser to project.
then:
using IniParser;
using IniParser.Model;
private void saveListViewItems(string path, ListView lv)
{
int i = 0;
string IPFrom;
string IPFromval;
string IPTO;
string IPTOval;
string Comment;
string Commentval;
string CheckState;
string CheckStateval;
int IPSectioncount;
var parser = new FileIniDataParser();
IniData data = parser.ReadFile(path);
while ( i < lv.Items.Count) {
if ((lv.Items[i].Selected) || (lv.Items[i].Checked))
{
CheckStateval = "1";
}
else
{
CheckStateval = "0";
}
CheckState = "";
CheckState = "CheckState";
CheckState += String.Join(CheckState, i);
IPFromval = lv.Items[i].SubItems[0].Text;
IPFromval = "";
IPFrom = "IPFrom";
IPFrom += String.Join(IPFrom, i);
IPFromval = lv.Items[i].SubItems[0].Text;
IPTOval = "";
IPTO = "IPTO";
IPTO += String.Join(IPTO, i);
IPTOval = lv.Items[i].SubItems[1].Text;
Commentval = "";
Comment = "Comment";
Comment += String.Join(Comment, i);
Commentval = lv.Items[i].SubItems[2].Text;
data["IP"][CheckState] = CheckStateval;
data["IP"][IPFrom] = IPFromval;
data["IP"][IPTO] = IPTOval;
data["IP"][Comment] = Commentval;
i++;
}
IPSectioncount = lv.Items.Count;
data["IP"]["IPSectionCount"] = IPSectioncount.ToString();
parser.WriteFile(path, data);
}
private void loadListViewItems(string path, ListView lv)
{
string IPFrom;
string IPTO;
string Comment;
string CheckState;
string IPSectioncount;
string row="";
var parser = new FileIniDataParser();
IniData data = parser.ReadFile(path);
IPSectioncount = data["IP"]["IPSectionCount"];
int m = Int32.Parse(IPSectioncount);
int i = 0;
while ( i < m )
{
IPFrom = "";
IPTO = "";
Comment = "";
row = "";
IPFrom = "IPFrom";
IPFrom += String.Join(IPFrom, i);
IPFrom = data["IP"][IPFrom];
IPTO = "IPTO";
IPTO += String.Join(IPTO, i);
IPTO = data["IP"][IPTO];
Comment = "Comment";
Comment += String.Join(Comment, i);
Comment = data["IP"][Comment];
CheckState = "CheckState";
CheckState += String.Join(CheckState, i);
CheckState = data["IP"][CheckState];
row = String.Join(",",IPFrom,IPTO,Comment);
lv.Items.Add(new ListViewItem(row.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)));
if (CheckState == "1")
{
lv.Items[i].Checked = true;
}
i++;
}
}

Related

How to interact with buttons created using a foreach loop?

I want these buttons created using a foreach loop from a list of items to access the information that is stored in these items.
I used a foreach loop to create buttons from a list of items that represent files in a directory and those items hold links to these files. My goal is to make pressing these buttons open a dialog with these files to write a line in them.
public List<mov.Movie> movies = new List<mov.Movie>() { };
private void writeReportToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (string file in Directory.EnumerateFiles(#"C:\Users\sloup\OneDrive\Desktop\MovieList", "*.txt"))
{
var lines = File.ReadAllLines(file);
string movieName = lines[0];
if (movies.Select(x => x.Name).Contains(movieName))
{
}
else
{
string movieLength = lines[1];
string movieYear = lines[2];
string movieReport = lines[3];
movies.Add(new mov.Movie(movieName, movieLength, movieYear, movieReport, #"C:\Users\sloup\OneDrive\Desktop\MovieList" + movieName + ".txt"));
}
}
int X = 1;
int Y = 1;
foreach (var movie in movies)
{
var movie1Button = new Button();
movie1Button.Text = movie.Name;
movie1Button.Font = new Font("Calibri", 12);
movie1Button.ForeColor = Color.Black;
movie1Button.Padding = new Padding(6);
movie1Button.AutoSize = true;
this.Controls.Add(movie1Button);
movie1Button.Location = new System.Drawing.Point(20, 50 * X);
X++;
movie1Button.Click += Movie1Button_Click;
var movie1Label = new Label();
movie1Label.Text = movie.Year;
movie1Label.Font = new Font("Calibri", 12);
movie1Label.ForeColor = Color.Black;
movie1Label.Padding = new Padding(6);
movie1Label.AutoSize = true;
this.Controls.Add(movie1Label);
movie1Label.Location = new System.Drawing.Point(200, 50 * Y);
Y++;
}
}
private void Movie1Button_Click(object? sender, EventArgs e)
{
string[] lines1 = File.ReadAllLines();
var lines = File.ReadAllLines();
string movieName = lines[0];
string movieLength = lines[1];
string movieYear = lines[2];
}
public class Movie
{
public string Name;
public string Length;
public string Year;
public string Report;
public string Link;
public Movie(string movieName, string movieLength, string movieYear, string movieReport, string movieLink)
{
Name = movieName;
Length = movieLength;
Year = movieYear;
Report = movieReport;
Link = movieLink;
}
}
You can use the Tag property to attach the movie object to each button in the loop:
movie1Button.Tag = movie;
afterwards in the click event grab the button from the sender and cast the Tag-object back to a Movie
private void Movie1Button_Click(object? sender, EventArgs e)
{
Button button = sender as Button
(if button != null)
{
Movie movie = button.Tag as Movie;
// do what ever you like afterwards
}
}

How to replace column data with blank inside C# script

I have been trying to add code to replace column data that has the word "null" to just a blank. I am not proficient in C#, so have no idea where to add it or how to code it. Below is the snippet of code that reads from the text file. I have no clue if the current code supports adding the replacement logic, so I am open to modifying the code to make it happen.
public override void PreExecute()
{
base.PreExecute();
int columnIndex;
string columnName = string.Empty;
string currentFile = Variables.vCurrentInputFile;
string[] currentRowValues;
string delimiter = Variables.vFileDelimiter;
Type fieldDataType;
string messageText;
DataRow row;
int upperBound;
bool skippedColumn = false;
var skippedColumns = new StringBuilder();
_FormatProvider = CultureInfo.GetCultureInfo(ComponentMetaData.LocaleID);
if (BuildImportBuffer())
{
try
{
using (var fileReader = new TextFieldParser(currentFile))
{
fileReader.SetDelimiters(delimiter);
fileReader.TrimWhiteSpace = false;
var fileColumns = fileReader.ReadFields();
while (!fileReader.EndOfData)
{
currentRowValues = fileReader.ReadFields();
if (currentRowValues != null)
{
upperBound = currentRowValues.GetUpperBound(0);
row = _BufferTable.NewRow();
try
{
var loopTo = upperBound;
for (columnIndex = 0; columnIndex <= loopTo; columnIndex++)
{
columnName = fileColumns[columnIndex];
if (!skippedColumn || skippedColumn && !skippedColumns.ToString().Contains(columnName))
{
fieldDataType = _BufferTable.Columns[columnName].DataType;
row[columnName] = Convert.ChangeType(currentRowValues[columnIndex].Trim(), fieldDataType, _FormatProvider);
}
}
}
I really need help with the code since I don't even know how to modify the current logic.

Can I make a dynamic combo Box from a text file?

I want to make a combo box like this:
But the boxes should not be hardcoded they should come from a text file like this:
Addition of data in text file should result in addition of combo Boxes. Also each comboBox should have the same list of options in it which are 1,2,3,4
I made the following class to read and write the text file, but I couldn't find any resources in the internet to turn these text files to combo Box.
public static string ReadFromTextFile(string path)
{
if (File.Exists(path))
{
string data;
using (StreamReader r = new StreamReader(path))
{
data = r.ReadToEnd();
}
if (data != "")
{
data = "[" + data + "]";
}
return data;
}
return null;
}
public static void WriteToTextFile(string path, string data, bool append = true, int count = 1)
{
if (!File.Exists(path))
{
var file = File.Create(path);
file.Close();
}
using (StreamWriter writer = new StreamWriter(path, append: append))
{
if (!append)
{
//remove opening bracket "[" from data passed
data = data.Trim().Substring(1, data.Trim().Length - 1);
//remove last bracket "]" from data passed
data = data.Trim().Substring(0, data.Trim().Length - 1);
}
if (count != 0)
{
data = data + ",";
}
writer.WriteLine(data);
}
}
public static DataTable ConvertToDataTable<T>(IList<T> data)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
if (data != null)
{
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
}
return table;
}
I don't have visual studio available now. So, I'll give you the way forward.
Read the line and split it into string array.
string[] arr= line.Split(",");
The first one (say Food) is the heading and the remaining are values.
Loop through the array.
for (int i=1;i<= arr.Length;i++)
{
}
Add it to the combobox items like cbo.Items.Add(arr[i]).
Loop through the lines in the file and you get the desired output.
You can use the string "Food"/"Water" as the Name property of the ComboBox to identify the each ComboBox.
Besides, note that should set a different Location for each ComboBox.
private void buttonCreateComboBox_Click(object sender, EventArgs e)
{
int locationX = 50;
int locationY = 10;
string line;
System.IO.StreamReader file =
new System.IO.StreamReader(#"C:\Users\Administrator\Desktop\test.txt");
while ((line = file.ReadLine()) != null)
{
// Remove the extra ','
string comboName = line.Substring(0, line.Length - 1);
ComboBox comboBox = new ComboBox();
comboBox.Name = comboName;
comboBox.Items.AddRange(new object[] { 1, 2, 3, 4 });
comboBox.Location = new Point(locationX, locationY);
this.Controls.Add(comboBox);
Label label = new Label();
label.Text = comboName;
label.Location = new Point(0, locationY);
this.Controls.Add(label);
locationY += 30;
}
file.Close();
}
If you want to access a specific ComboBox, you can call Control.ControlCollection.Find(String, Boolean) Method to get it.
private void buttonGetComboWaterText_Click(object sender, EventArgs e)
{
ComboBox comboWater = (ComboBox)this.Controls.Find("Water", true)[0];
MessageBox.Show(comboWater.Text);
}
Without going into details (don't know why you need DataTable etc.) I will answer your main question from title.
This is how my textfile looks, no need for comma if you read line by line:
public void ReadFromTextFile(string path)
{
if (File.Exists(path))
{
using (StreamReader r = new StreamReader(path))
{
String line;
while ((line = r.ReadLine()) != null)
{
CreateComboBox(line.ToString());
}
}
}
}
public void CreateComboBox(string definition)
{
var combo = new ComboBox();
combo.Name = definition;
combo.Items.AddRange(new object[] { "1", "2", "3", "4" });
var label = new Label();
label.Text = definition;
this.flowLayoutPanel1.Controls.Add(label);
this.flowLayoutPanel1.Controls.Add(combo);
}
private void Form1_Load(object sender, EventArgs e)
{
ReadFromTextFile(#"c:\temp\MyTest.txt");
}
Use File.ReadAllLines(...) to short the txt read.
Point to control the position.
Attaches a delegate to SelectedIndexChanged that I imagine you will need for the next step.
private void Form1_Load(object sender, EventArgs e)
{
var lines = File.ReadAllLines(#"src.txt").Select(str => str.Replace(",", "")).ToList();
Label lbl, lastLbl = null;
ComboBox combo, lastCombo = null;
for (int i = 0; i < lines.Count(); i++)
{
lbl = new Label();
lbl.Text = lines[i];
if (i > 0) // adjust position
lbl.Location = new Point(lastLbl.Location.X, lastLbl.Location.Y + lastLbl.Height);
this.Controls.Add(lbl);
lastLbl = lbl;
combo = new ComboBox();
combo.DataSource = new List<int>() { 1, 2, 3, 4 };
if (i > 0) // adjust position
combo.Location = new Point(lastCombo.Location.X, lastCombo.Location.Y + lastCombo.Height);
else
combo.Location = new Point(lbl.Width + 5, 0);
//combo.SelectedIndexChanged += (s, a) => { }; // action you may need
this.Controls.Add(combo);
lastCombo = combo;
}
}

I want to load a text file into a data grid and apply a regular expression

string[] s = File.ReadAllLines(ofdl.FileName);
List<code> codes = new List<code>();
string textfile = ofdl.FileName;
var textvalues = s;
foreach (var item in textvalues)
{
codes.Add(new code() { Value = RemoveEmptyLines(item) });
}
dataGrid.ItemsSource = codes;
under_label.Content = textfile;
under_label1.Content = codes.Count();
private string RemoveEmptyLines(string lines)
{
return lines = Regex.Replace(lines, #"\n\s.+", "");
}
I want to load a text file into a data grid and apply a regular expression
but this code don't work for me
you don't need Regex to search for empty strings. String.IsNullOrWhiteSpace() method will do.
string[] lines = File.ReadAllLines(ofdl.FileName);
var codes = lines.Where(s => !String.IsNullOrWhiteSpace(s)).ToList();
dataGrid.ItemsSource = codes;
under_label.Content = ofdl.FileName;
under_label1.Content = codes.Count;
datagrid
I want to exclude the part of the circle separately
List<code> codes = new List<code>();
string[] s = File.ReadAllLines(ofdl.FileName);
string textfile = ofdl.FileName;
var textvalues = s;
foreach (var item in textvalues)
{
codes.Add(new code() { Value = item});
}
dataGrid.ItemsSource = codes;
}
}
}
private void streams()
{
}
private string RemoveEmptyLines(string lines)
{
return lines = Regex.Replace(lines, #"\n\s.+", "");
}

Program stops working after selected index change second time listview c#

i have a problem that i change selected index in listview it works fine when i change first time but when i change second time it says "InvalidArgument=Value of '0' is not valid for 'index'."
the code is this ;
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
strpath is way to desktop
try
{
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
}
catch
{
}
i just fixed it like this

Categories

Resources