How to delete selected Item from a listbox - c#

I have created a DeleteSlectedItemListBox Method below which has a code that deleted a selected item in the list-box when delete button has been clicked. However it does not seem like its working.
The code has to delete whats on the list-box as well in the text-file.
How do I do that ?
private void DeleteSelectedItemListBox()
{
DataTable dt = new DataTable();
string FileName = (#"C: \Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text");
StreamReader streamReader = new StreamReader(FileName);
string line = "";
int Counter = -1;
while ((line = streamReader.ReadLine()) != null)
{
foreach (var item in line)
{
if (item.ToString() == SelectedItem.ToString())
{
Counter--;
dt.Clear();
ListBox.Remove(line);
}
}
}
}

If you are using MVVM pattern you can bind in XAML selected item and your list like ObservableCollention. <ListBox ItemsSource="{Binding YourList}" SelectedItems="{Binding YourSelectedItem}"></ListBox>
Then in your deleting method you can try:
private void DeleteSelectedItemListBox()
{
var deletingNumber = YourList.IndexOf(YourSelectedItem);
var allLines = File.ReadAllLines(path).ToList();
allLines.RemoveAt(deletingNumber);
File.WriteAllLines(path,allLines.ToArray());
}

while (listBox1.SelectedItems.Count > 0)
{
var index = listBox1.Items.IndexOf(listBox1.SelectedItem);
listBox1.Items.RemoveAt(index);
RemoveTextLine(index);
}
private void RemoveTextLine(int index){
using(var sr = new StreamReader("C:\Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\Personal.text"))
using(var sw = new StreamWriter("C:\Users\StanleyM\Desktop\PhoneBook\PhoneBook\bin\Debug\temp.text"))
{
int line=0;
while((sr.ReadLine()) != null)
{
if(line != index)
sw.WriteLine(line);
line ++;
}
}
File.Delete("Personal.txt");
File.Move(tempFile, "Personal.txt");
}
Try This

Related

asp.net c# txt file to dropdownlist:

I need to populate a drop down list with a txt file. I tried this but it isn't working.
protected void DropDownListCOUNTRY_SelectedIndexChanged(object sender, EventArgs e)
{
List<string> country = new List<string>();
country = File.ReadAllLines("../App_Data/txt/CountryList.txt").Select(x => x.Split('_')[0]).ToList();
foreach (string countrysingle in country)
{
DropDownListCOUNTRY.Items.Add(new ListItem(countrysingle, countrysingle));
}
}
This is the VB code that works in C#
if (this.IsPostBack == false)
{
string path = MapPath("~/App_Data/txt/CountryList.txt");
FileStream fp = new FileStream(path, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fp);
string data;
while ((data = reader.ReadLine()) != null)
{
string[] v = data.Split(',');
foreach (string entry in v)
{
DropDownListCOUNTRY.Items.Add(entry);
}
}
reader.Close();
fp.Close();
}
The VB code in my initial question works.
I think you have to give variable declaration also in foreach loop like below
foreach (string countrysingle in country) {
DropDownListCOUNTRY.Items.Add(countrysingle);
}

How to prevent it from being added 2 times in listview

I ama getting data from news website with webrequest and show my listview. When user click button , first of all I am getting all news and show my listview, after e.g 15 min user click button again. I am checking my news list if news is exits, I am showing messagebox "There is no fresh news". but if there is a news put all news list in listview again. For example. first lisview count is 75 . and there is 2 fresh news, normally my listview should 77. but listview shows 152. Where is my mistake. can you help me ?
my button click event
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
foreach (var item in list)
{
listView1.Items.Add(item);
}
}
this is my class
public static Dictionary<string, Hurriyet> HurriyetHaberList = new Dictionary<string, Hurriyet>();
public List<ListViewItem> GetTagsHurriyet()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://www.hurriyet.com.tr/rss/gundem");
XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");
if (el != null)
{
el.ParentNode.RemoveChild(el);
}
XmlNode Haberler = el.SelectSingleNode("channel");
List<ListViewItem> listViewItems = new List<ListViewItem>();
bool degismiMi = false;
foreach (XmlNode haber in Haberler.SelectNodes("item"))
{
Hurriyet h = new Hurriyet();
ListViewItem li = new ListViewItem();
//li.Text = haber.SelectSingleNode("title").InnerText;
h.Title = haber.SelectSingleNode("title").InnerText;
if (haber.SelectSingleNode("description").InnerText.Contains(">"))
{
var str1 = haber.SelectSingleNode("description").InnerText.IndexOf(">");
var str2 = haber.SelectSingleNode("description").InnerText.Substring(str1 + 4);
//li.SubItems.Add(str2);
}
else
{
//li.SubItems.Add(haber.SelectSingleNode("description").InnerText);
h.Description = haber.SelectSingleNode("description").InnerText;
}
h.Link = haber.SelectSingleNode("link").InnerText;
//li.SubItems.Add(haber.SelectSingleNode("link").InnerText);
var format = DateTime.Parse(haber.SelectSingleNode("pubDate").InnerText.ToString());
//li.SubItems.Add(format.ToString());
h.PubDate = format;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(haber.SelectSingleNode("link").InnerText);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
string begenningKeyword = "<meta name=\"keywords\" content=\"";
var tags = final_response.IndexOf(begenningKeyword);
var final_response2 = final_response.Substring(tags + begenningKeyword.Length);
var tagsBol = final_response2.IndexOf("\" />");
var lastTags = final_response2.Substring(0, tagsBol);
int yer1;
if (lastTags != string.Empty)
{
h.Tags = lastTags;
//li.SubItems.Add(lastTags);
}
else
{
yer1 = final_response.IndexOf("tagsContainer");
if (yer1 == -1)
{
continue;
}
else
{
yer1 = final_response.IndexOf("tagsContainer");
int yer2 = final_response.IndexOf("</div>", yer1);
var tagDiv = final_response.Substring(yer1, yer2 - yer1);
List<string> listele = new List<string>();
for (int i = 0; i < tagDiv.Length; i++)
{
var firstSpan = tagDiv.IndexOf("<span>");
var firstSpan2 = tagDiv.IndexOf("<span itemprop=\"keywords\">");
if (firstSpan != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan);
var lastSpan = tagDiv.Substring(firstSpan, secondSpan - firstSpan);
var remo = lastSpan.Replace("<span>", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else if (firstSpan2 != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan2);
var lastSpan = tagDiv.Substring(firstSpan2, secondSpan - firstSpan2);
var remo = lastSpan.Replace("<span itemprop=\"keywords\">", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else
break;
}
string c = string.Empty;
foreach (var item in listele)
{
c += item + ",";
}
//li.SubItems.Add(c.Substring(0, c.Length - 1));
h.Tags = c.Substring(0, c.Length - 1);
}
}
if (HurriyetHaberList.ContainsKey(haber.SelectSingleNode("link").InnerText) == false)
{
HurriyetHaberList.Add(haber.SelectSingleNode("link").InnerText, h);
degismiMi = true;
//listViewItems.Insert(0,li);
}
}
if (!degismiMi)
{
MessageBox.Show("Haberlerde değişiklik olmadı");
}
else
{
listViewItems.Clear();
foreach (var item in HurriyetHaberList.OrderByDescending(x => x.Value.PubDate).ToList())
{
ListViewItem lstItem = new ListViewItem();
lstItem.Text = item.Value.Title;
lstItem.SubItems.Add(item.Value.Description);
lstItem.SubItems.Add(item.Value.Link);
lstItem.SubItems.Add(item.Value.PubDate.ToString());
lstItem.SubItems.Add(item.Value.Tags);
listViewItems.Add(lstItem);
}
}
return listViewItems;
}
Screenshot
The problem is that your code
hurriyet.GetTagsHurriyet();
Delivers all 77 Items and this result is than added to your list Control with the below code
foreach (var item in list)
{
listView1.Items.Add(item);
}
You need to clear your listView1 or make sure that the method GetTagsHurriyet() only returns new items.
So either do the following:
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
listView1.Items.Clear(); //<-- added line
foreach (var item in list)
{
listView1.Items.Add(item);
}
}
Or in your GetTagsHurriyet() method only fill the list if your dictionary says it is new:
if (HurriyetHaberList.ContainsKey(haber.SelectSingleNode("link").InnerText) == false)
{
HurriyetHaberList.Add(haber.SelectSingleNode("link").InnerText, h);
degismiMi = true;
//listViewItems.Insert(0,li);
//add items to listViewItems here and drop the code below
}
Edit:
Based on the comment below:
Something like this:
(Didnt test the code, removed some comments to make it smaller also changed some stuff here and there)
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
if (!list.Any())
MessageBox.Show("Haberlerde değişiklik olmadı");
else
{
foreach (var item in list)
listView1.Items.Add(item);
}
}
public static Dictionary<string, Hurriyet> HurriyetHaberList = new Dictionary<string, Hurriyet>();
public List<ListViewItem> GetTagsHurriyet()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("http://www.hurriyet.com.tr/rss/gundem");
XmlElement el = (XmlElement)xdoc.SelectSingleNode("/rss");
if (el != null)
el.ParentNode.RemoveChild(el);
XmlNode Haberler = el.SelectSingleNode("channel");
List<Hurriyet> newHurriyets = new List<Hurriyet>();
bool degismiMi = false;
foreach (XmlNode haber in Haberler.SelectNodes("item"))
{
var link = haber.SelectSingleNode("link").InnerText;
if (HurriyetHaberList.ContainsKey(link))
continue;
Hurriyet h = new Hurriyet();
h.Title = haber.SelectSingleNode("title").InnerText;
if (!haber.SelectSingleNode("description").InnerText.Contains(">"))
h.Description = haber.SelectSingleNode("description").InnerText;
h.Link = link;
var format = DateTime.Parse(haber.SelectSingleNode("pubDate").InnerText.ToString());
h.PubDate = format;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(link);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string final_response = stream.ReadToEnd();
string begenningKeyword = "<meta name=\"keywords\" content=\"";
var tags = final_response.IndexOf(begenningKeyword);
var final_response2 = final_response.Substring(tags + begenningKeyword.Length);
var tagsBol = final_response2.IndexOf("\" />");
var lastTags = final_response2.Substring(0, tagsBol);
int yer1;
if (!string.IsNullOrEmpty(lastTags))
h.Tags = lastTags;
else
{
yer1 = final_response.IndexOf("tagsContainer");
if (yer1 == -1)
continue;
yer1 = final_response.IndexOf("tagsContainer");
int yer2 = final_response.IndexOf("</div>", yer1);
var tagDiv = final_response.Substring(yer1, yer2 - yer1);
List<string> listele = new List<string>();
for (int i = 0; i < tagDiv.Length; i++)
{
var firstSpan = tagDiv.IndexOf("<span>");
var firstSpan2 = tagDiv.IndexOf("<span itemprop=\"keywords\">");
if (firstSpan != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan);
var lastSpan = tagDiv.Substring(firstSpan, secondSpan - firstSpan);
var remo = lastSpan.Replace("<span>", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else if (firstSpan2 != -1)
{
var secondSpan = tagDiv.IndexOf("</a>", firstSpan2);
var lastSpan = tagDiv.Substring(firstSpan2, secondSpan - firstSpan2);
var remo = lastSpan.Replace("<span itemprop=\"keywords\">", "");
var remo2 = remo.Replace("</span>", "");
listele.Add(remo2);
tagDiv = tagDiv.Replace(lastSpan, "");
}
else
break;
}
h.Tags = string.Join(",", listele);
}
}
HurriyetHaberList.Add(link, h);
newHurriyets.Add(h);
}
List<ListViewItem> listViewItems = new List<ListViewItem>();
foreach (var item in newHurriyets.OrderByDescending(x => x.PubDate))
{
ListViewItem lstItem = new ListViewItem();
lstItem.Text = item.Title;
lstItem.SubItems.Add(item.Description);
lstItem.SubItems.Add(item.Link);
lstItem.SubItems.Add(item.PubDate.ToString());
lstItem.SubItems.Add(item.Tags);
listViewItems.Add(lstItem);
}
return listViewItems;
}
You can clear items before filling:
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
listView1.Items.Clear(); // Clear items
foreach (var item in list)
{
listView1.Items.Add(item);
}
}
otherwise you would have to check if listView1 does not have item you want to add (not by reference, maybe some property?). This case however will not handle deleting items
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
foreach (var item in list)
{
if(!IsItemPresent(item)) // You should implement this method somehow
listView1.Items.Add(item);
}
}
listView1 should clear before u add new items. becose their was old data.
put this code listView1.Clear(); before start loop.
listView1.Clear();
private void btnHurriyet_Click(object sender, EventArgs e)
{
Hurriyet hurriyet = new Hurriyet();
List<ListViewItem> list = hurriyet.GetTagsHurriyet();
listView1.Clear();
foreach (var item in list)
{
listView1.Items.Add(item);
}
}

Execute Method (that updating datagridview) from Another Form C#

I have 2 form. MainPage form contains datagridview and fetchTradeReport method to populate/refresh datagrid, while ColumnSettings form use to configure which datagridviewcolumn that user want to be visible or not. I have "Apply Changes" button in ColumnSettings form, and I include fetchTradeReport method in the click event. But, the datagrid still the same and don't change after I clicked it.
This is my fetchTradeReport method
public void fetchTradeReport()
{
try
{
TTransport transport = new TSocket(address, port);
TProtocol protocol = new TBinaryProtocol(transport);
CacheService.Client client = new CacheService.Client(protocol);
transport.Open();
List<string> transactTime = new List<string>();
SearchCriteria criteria = new SearchCriteria();
criteria.Filters = new List<Filter>();
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
if (Convert.ToString(tradeStatusCB.Text) != "")
setTradeStatusFilter(criteria, (TradeReportStatus)Enum.Parse(typeof(TradeReportStatus), Convert.ToString(tradeStatusCB.Text)));
if (platformTB.Text != "")
setPlatformFilter(criteria, platformTB.Text);
if (exchangeTB.Text != "")
criteria.Exchange = exchangeTB.Text;
if (productTB.Text != "")
criteria.Product = productTB.Text;
if (accountTB.Text != "")
criteria.Account = accountTB.Text;
if (orderidTB.Text != "")
setOrderIDFilter(criteria, orderidTB.Text);
if (tradereportidTB.Text != "")
setReportIDFilter(criteria, tradereportidTB.Text);
if (tradedateDTP.Text.Length != 1)
criteria.TradeDate = Convert.ToInt32(tradedateDTP.Value.ToString("yyyyMMdd"));
var tradeList = client.getTradeReports(criteria);
tradeGridView.DataSource = tradeList;
foreach (DataGridViewRow row in tradeGridView.Rows)
{
double time = Convert.ToDouble(row.Cells["TransactTime"].Value);
string dtm = dt.AddSeconds(time).ToLocalTime().ToString();
transactTime.Add(dtm);
}
tradeGridView.Columns.Remove("TransactTime");
if(tradeGridView.Columns.Contains("TransactionTime"))
tradeGridView.Columns.Remove("TransactionTime");
tradeGridView.Columns.Add("TransactionTime", "TransactionTime");
tradeGridView.Columns["TransactionTime"].ValueType = typeof(String);
int i = 0;
foreach (DataGridViewRow row in tradeGridView.Rows)
{
row.Cells["TransactionTime"].Value = transactTime[i];
i++;
}
int counter = 0;
string line;
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\\ColumnSettings.config"))
{
StreamReader readFile = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\\ColumnSettings.config");
while ((line = readFile.ReadLine()) != null)
{
string columnName = line.Substring(0, line.Length - 2);
tradeGridView.Columns[columnName].DisplayIndex = counter;
if (line.Split('-').Last() == "1")
tradeGridView.Columns[columnName].Visible = true;
else
tradeGridView.Columns[columnName].Visible = false;
counter++;
}
readFile.Close();
}
else
collectColumnName();
transport.Close();
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace);
}
}
And this is how I call it in "Apply Changes" button click event in ColumnSettings form
new MainPage(GetConnectionString.address, GetConnectionString.port).fetchTradeReport();
Sorry if my English bad. Any help appreciated. Thanks.

MahApps DataGrid unable to take user input and write to csv

Any help would be greatly appreciated. Sorry, if my code is junior. I am new to C#.
Problem
I've dynamically create multiple DataGrids in a flyout, using MahApps. The DataGrids are populated by CSV files (ConvertCSVtoDataTable()). I want the user to be able to make changes to the DataGrids and when they are done, The DataGrids values will replace the CSV files(UpdateDataGridParameter()).
UI Tree: Flyout > StackPanel > GroupBox > DataGrid
Issue
DG.SelectAllCells() does not select from the user changed DataGrid. How can I get the VISUAL UI representation of the DataGid or bind the DT property to a data change event. I hope I explained this correctly. If you have any questions that can help me please post and I will respond quickly. Thanks
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace SpiderRoll.Classes
{
public class DataGridProperties
{
private int IDValue;
public int ID
{
get { return IDValue; }
set { IDValue = value; }
}
private string HeaderValue;
public string Header
{
get { return HeaderValue; }
set { HeaderValue = value; }
}
private string DescriptionValue;
public string Description
{
get { return DescriptionValue; }
set { DescriptionValue = value; }
}
private string NameValue;
public string Name
{
get { return NameValue; }
set { NameValue = value; }
}
private string FilePathValue;
public string FilePath
{
get { return FilePathValue; }
set { FilePathValue = value; }
}
private DataTable DTValue;
public DataTable DT
{
get
{
return DTValue;
}
set
{
DTValue = value;
}
}
public static DataGridProperties DataGridObject(List<DataGridProperties> TBP, int ID = 0, string Name = "")
{
foreach (var tb in TBP)
{
if (tb.ID == ID || tb.Name == Name)
{
return tb;
}
}
return null;
}
public static int FindDataGridID(List<DataGridProperties> DGP, string Name = "")
{
int i = 0;
foreach (var dg in DGP)
{
if (dg.Name == Name)
{
return i;
}
i++;
}
return -1;
}
public static GroupBox DataGridPropertieStackPanel(DataGridProperties DataGrid) // DataGridProperties DataGrid
{
GroupBox GB = new GroupBox();
GB.Header = DataGrid.Header;
StackPanel SPMain = new StackPanel();
SPMain.Orientation = System.Windows.Controls.Orientation.Vertical;
System.Windows.Controls.Label LBDescription = new System.Windows.Controls.Label();
LBDescription.Content = DataGrid.Description;
LBDescription.Margin = new Thickness(10, 0, 0, 0);
SPMain.Children.Add(LBDescription);
StackPanel SP = new StackPanel();
SP.Name = DataGrid.Name;
SP.Orientation = System.Windows.Controls.Orientation.Horizontal;
SP.Margin = new Thickness(10);
System.Windows.Controls.DataGrid DG = new System.Windows.Controls.DataGrid();
DG.Name = DataGrid.Name;
DG.CanUserAddRows = false;
DG.ItemsSource = DataGrid.DT.DefaultView;
SP.Children.Add(DG);
SPMain.Children.Add(SP);
GB.Content = SPMain;
return GB;
}
public static DataTable ConvertCSVtoDataTable(string FilePath)
{
StreamReader sr = new StreamReader(FilePath);
string[] headers = sr.ReadLine().Split(',');
string[] firstLine = sr.ReadLine().Split(',');
DataTable dt = new DataTable();
DataColumn column = new DataColumn();
DataRow fl = dt.NewRow();
int idx = 0;
foreach (string header in headers)
{
//If bool is in first row, turn the column into a checkbox.
if (firstLine[idx].ToLower() == "true" || firstLine[idx].ToLower() == "false")
{
column = dt.Columns.Add(header, typeof(bool));
}
else
{
column = dt.Columns.Add(header, typeof(string));
column.ReadOnly = true;
}
if (header.EndsWith("~"))
{
column.ReadOnly = true;
}
//Reading and building the first row
fl[idx] = firstLine[idx];
idx++;
}
//Adding first row
dt.Rows.Add(fl);
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
string[] rows = line.Split(',');
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dt.Rows.Add(dr);
}
return dt;
}
public static void UpdateDataGridParameter(DataGrid DG)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = DG.Columns.Cast<DataGridColumn>().
Select(column => column.Header.ToString());
sb.AppendLine(string.Join(",", columnNames));
DG.UnselectAllCells();
DG.SelectAllCells();
foreach (DataRowView row in DG.SelectedItems)
{
IEnumerable<string> fields = row.Row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
DG.UnselectAllCells();
var filePath = #"C:\IO\" + DG.Name + ".csv";
File.WriteAllText(filePath, sb.ToString());
}
}
}
In Class Bundle, I create a list of DataGrids
private List<DataGridProperties> dataGridList;
public List<DataGridProperties> DataGridList
{
get
{
return dataGridList;
}
set
{
dataGridList = value;
}
}
In Main, I iterate the DataGridlist and populate StackPanels by calling the DataGridPropertieStackPanel function.
foreach (var item in bundle.DataGridList)
{
if (item.Name == DataGrid.Name)
{
sPanelParameters.Children.Add(DataGridProperties.DataGridPropertieStackPanel(item));
}
}
Your DataGrid updates the binded DataView once you change the values. You don't have to select and unselect the grid rows, just access the dataview directly. Slightly changed version of your code:
public static void UpdateDataGridParameter(DataGrid dataGrid)
{
StringBuilder sb = new StringBuilder();
var dataView = dataGrid.ItemsSource as DataView;
var columnNames = dataView.Table.Columns
.Cast<DataColumn>()
.Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRowView row in dataView)
{
IEnumerable<string> fields = row.Row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
var filePath = #"C:\IO\" + dataGrid.Name + ".csv";
File.WriteAllText(filePath, sb.ToString());
}

Read File and display contents

I want that when I click the button "List all Customers", the code should read the Customer.csv file and display the information on the form called "List All Customers".
How can I do that?
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
int count = 0;
using (StreamReader sr = File.OpenText(#"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
Customer tempCust = new Customer();
tempCust.customerName = lineHolder[0];
tempCust.customerAddress = lineHolder[1];
tempCust.customerZip = Convert.ToInt32(lineHolder[2]);
myCustArray[count] = tempCust;
count++;
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
I'm not sure what kind of control you want to display this data in but your method could just return a list of Customer, then you can add to a ListBox, ListView or DataGrid
public static IEnumerable<Customer> LoadCustomers(string filename)
{
if (File.Exists(filename))
{
foreach (var line in File.ReadAllLines(filename).Where(l => l.Contains(',')))
{
var splitLine = line.Split(',');
if (splitLine.Count() >= 3)
{
yield return new Customer
{
customerName = splitLine[0].Trim(),
customerAddress = splitLine[1].Trim(),
customerZip = Convert.ToInt32(splitLine[2].Trim())
};
}
}
}
}
ListBox
listBox1.DisplayMember = "customerName";
listBox1.Items.AddRange(LoadCustomers(#"G:\Customers.csv").ToArray());
First, take advantage of the list object:
public static void ReadFile()
{
StreamReader sr = File.OpenText("Customer.csv");
}
public static void LoadCustomers()
{
try
{
if (File.Exists("Customer.csv"))
{
string temp = null;
var retList = new List<Customer>();
using (StreamReader sr = File.OpenText(#"Customer.csv"))
{
while ((temp = sr.ReadLine()) != null)
{
temp = temp.Trim();
string[] lineHolder = temp.Split(',');
retlist.add(new Customer(){
customerName = linerHolder[0],
customerAddress = lineHolder[1],
customerZip = Convert.ToInt32(lineHolder[2])
});
}//end for loop
}
}
else
{
File.Create("Customer.csv");
}
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("File Loading Error: " + e.Message);
}
}
just wrap it up in a class, call if from the controller and populate up the results. Depending on how often you will be updating this data, you might look into caching it, so you don't have to run this process every X seconds for each user.

Categories