Faster way of reading csv to grid - c#

I have following in Windows Forms .NET 3.5
It works fine for csv with records less than 10,000 but is slower for records above 30,000.
Input csv file can can any records between 1 - 1,00,000 records
Code currently used :
/// <summary>
/// This will import file to the collection object
/// </summary>
private bool ImportFile()
{
try
{
String fName;
String textLine = string.Empty;
String[] splitLine;
// clear the grid view
accountsDataGridView.Rows.Clear();
fName = openFileDialog1.FileName;
if (System.IO.File.Exists(fName))
{
System.IO.StreamReader objReader = new System.IO.StreamReader(fName);
do
{
textLine = objReader.ReadLine();
if (textLine != "")
{
splitLine = textLine.Split(',');
if (splitLine[0] != "" || splitLine[1] != "")
{
accountsDataGridView.Rows.Add(splitLine);
}
}
} while (objReader.Peek() != -1);
}
return true;
}
catch (Exception ex)
{
if (ex.Message.Contains("The process cannot access the file"))
{
MessageBox.Show("The file you are importing is open.", "Import Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show(ex.Message);
}
return false;
}
}
Sample Input file :
18906,Y
18908,Y
18909,Y
18910,Y
18912,N
18913,N
Need some advice on optimizing this code for fast reads & view in grid.

List<string[]> rows = File.ReadAllLines("Path").Select(x => x.Split(',')).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("1");
dt.Columns.Add("2");
rows.ForEach(x => {
dt.Rows.Add(x);
});
dgv.DataSource = dt;
Try that, I suspected that you have some form of column names in the datagrid for now I just made them 1 and 2.
To filter as per your original code use:
List<string[]> rows = File.ReadAllines("Path").Select(x => x.Split(',')).Where(x => x[0] != "" && x[1] != "").ToList();
To get your columns from the DataGridView
dt.Columns.AddRange(dgv.Columns.Cast<DataGridViewColumn>().Select(x => new DataColumn(x.Name)).ToArray());

There isn't much to optimize in regards to speed, but following is much more readable. If it is too slow, it probably isn't the method reading the file, but your WinForm that needs to display >30k records.
accountsDataGridView.Rows.Clear();
using (FileStream file = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096))
using (StreamReader reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
var fields = reader.ReadLine().Split(',');
if (fields.Length == 2 && (fields[0] != "" || fields[1] != ""))
{
accountsDataGridView.Rows.Add(fields);
}
}
}

You can try to use SuspendLayout() and ResumeLayout() Methods.
From MSDN Documentation
"The SuspendLayout and ResumeLayout methods are used in tandem to suppress multiple Layout events while you adjust multiple attributes of the control. For example, you would typically call the SuspendLayout method, then set the Size, Location, Anchor, or Dock properties of the control, and then call the ResumeLayout method to enable the changes to take effect."
accountsDataGridView.SuspendLayout();
accountsDataGridView.Rows.Clear();
// .....
// in the end after you finished populating your grid call
accountsDataGridView.ResumeLayout();

Instead of putting the data directly into the grid you should take a look at the VirtualMode of the DataGridView.
In your code you're doing two things at one time (read the file, fill the grid), which leads to your freezed gui. Instead you should put the grid into the virtual mode and read the file within a BackgroundWorker into a list which holds the data for the grid. The background worker can after each line read update the virtual size of the grid, which allows to already see the data while the grid is loading. By using this approach you'll getting a smooth working grid.
Below you'll find an example which just needs to be filled into a form that uses a DataGridView with two text columns, a BackgroundWorker and a Button:
public partial class FormDemo : Form
{
private List<Element> _Elements;
public FormDemo()
{
InitializeComponent();
_Elements = new List<Element>();
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.ReadOnly = true;
dataGridView.VirtualMode = true;
dataGridView.CellValueNeeded += OnDataGridViewCellValueNeeded;
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork += OnBackgroundWorkerDoWork;
backgroundWorker.ProgressChanged += OnBackgroundWorkerProgressChanged;
backgroundWorker.RunWorkerCompleted += OnBackgroundWorkerRunWorkerCompleted;
}
private void OnBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
var filename = (string)e.Argument;
using (var reader = new StreamReader(filename))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
var parts = line.Split(',');
if (parts.Length >= 2)
{
var element = new Element() { Number = parts[0], Available = parts[1] };
_Elements.Add(element);
}
if (_Elements.Count % 100 == 0)
{
backgroundWorker.ReportProgress(0);
}
}
}
}
private void OnBackgroundWorkerProgressChanged(object sender, ProgressChangedEventArgs e)
{
dataGridView.RowCount = _Elements.Count;
}
private void OnBackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
dataGridView.RowCount = _Elements.Count;
button.Enabled = true;
}
private void OnButtonLoadClick(object sender, System.EventArgs e)
{
if (!backgroundWorker.IsBusy
&& DialogResult.OK == openFileDialog.ShowDialog())
{
button.Enabled = false;
backgroundWorker.RunWorkerAsync(openFileDialog.FileName);
}
}
private void OnDataGridViewCellValueNeeded(object sender, DataGridViewCellValueEventArgs e)
{
var element = _Elements[e.RowIndex];
switch (e.ColumnIndex)
{
case 0:
e.Value = element.Number;
break;
case 1:
e.Value = element.Available;
break;
}
}
private class Element
{
public string Available { get; set; }
public string Number { get; set; }
}
}

Related

Not sure why this Radio Button is throwing an error?

I am currently making a fitness class booking system for some study I am doing so please bare with me.
I have done most of the code but I am having this strange issue with my 2nd radio button for selecting what class you want.
I have set up my code so a message box appears if the Member ID you have entered is already registered to the fitness class you have selected. For my RadioButton1 (rbCardioClass) and RadioButton2 (rbPilatesClass), the error message box works great and works as it should. But my RadioButton2 (rbSpinClass) will make the error message box appear everytime, even if the MemberID is not associated to the 'Spin Class'.
I have tried different uses of if statements, different radio buttons etc but can't seem to get it to work the way I want.
If I go to my servicesErrorCheck(string[] description)method and just the temp variable to true all radio buttons save to the database table correctly BUT I then lose my erroring, which makes me thinks it is something to do with the way I have set up the message box, maybe.
Here is a screenshot of the prototype form just for reference. FitnessClassBooking Form
Here is a screenshot of the table while the app is running App Running Fitness Form
Here is the error being thrown with MemberID that has no 'Spin' class associated with it App Running Error
Here is my code in question -
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.Data.SqlClient;
using System.Configuration;
namespace Membership_Formv2
{
public partial class FitnessClassBooking : Form
{
public FitnessClassBooking()
{
InitializeComponent();
}
private void bMainMenu_Click(object sender, EventArgs e)
{
new MainMenu().Show();
this.Hide();
}
private void fitnessInformationBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.fitnessInformationBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.databaseDataSet);
}
private void FitnessClassBooking_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'databaseDataSet.Members' table. You can move, or remove it, as needed.
this.membersTableAdapter.Fill(this.databaseDataSet.Members);
// TODO: This line of code loads data into the 'databaseDataSet.FitnessInformation' table. You can move, or remove it, as needed.
this.fitnessInformationTableAdapter.Fill(this.databaseDataSet.FitnessInformation);
}
private void fitnessInformationDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private string descriptionfit()
{
string className = "";
if (rbCardioClass.Checked == true)
{
className = "Cardio";
}
else if (rbSpinClass.Checked == true)
{
className = "Spin";
}
else if (rbPilatesClass.Checked == true)
{
className = "Pilates";
}
return className;
}
private string classDescription()
{
string serviceSeletionString = "Class";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
return serviceSeletionString;
}
private bool errorCheckingID()
{
bool statusDB = true;
//Getting row info from MembersTa table
DatabaseDataSet.MembersRow newEntry = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox3.Text));
//Getting information from BookingTa table
if (newEntry == null)
{
statusDB = false;
return (statusDB);
}
return (statusDB);
}
public bool servicesErrorCheck(string[] description)
{
bool temp = true;
string serviceSeletionString = "";
if (rbCardioClass.Checked == true)
{
serviceSeletionString = rbCardioClass.Text;
this.Refresh();
}
else if (rbSpinClass.Checked == true)
{
serviceSeletionString = rbSpinClass.Text;
this.Refresh();
}
else if (rbPilatesClass.Checked == true)
{
serviceSeletionString = rbPilatesClass.Text;
this.Refresh();
}
for (int t = 0; t < description.Length; t++)
{
if (serviceSeletionString.Contains(description[t].Trim()))
{
temp = false;
break;
}
}
return (temp);
}
private string originalaccesdb()
{
string a = "";
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = descriptionfit();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
return a;
}
private string[] accessDB()
{
int t = 0;
int temp;
string[] servicesList = { "n", "n", "n" }; //This variable will store the data
//Same code too extract table information
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox3.Text))
{
//Store inside the array all the services/description against the ID.
//Note that this array will remain "" for all the elements inside the array
//if no descritopn/services (i.e., record) is found against the input ID
servicesList[t] = r["Description"].ToString();
t = t + 1;
}
}
return (servicesList);
}
private void button1_Click(object sender, EventArgs e)
{
string text = textBox1.Text;
textBox1.Text = "";
int a = Int32.Parse(textBox2.Text);
DatabaseDataSet.MembersRow newID = databaseDataSet.Members.FindByMemberID(Int32.Parse(textBox2.Text));
string booking = "";
int temp;
foreach (DataRow r in databaseDataSet.FitnessInformation.Rows)
{
temp = Int32.Parse(r["MemberID"].ToString());
if (temp == Int32.Parse(textBox2.Text))
{
booking = r["Description"].ToString() + ", " + booking;
}
}
textBox1.Text = "Member ID is: " + (newID.MemberID).ToString() + Environment.NewLine +
"First Name is: " + (newID.First_Name).ToString() + Environment.NewLine +
"Last Name is: " + (newID.Last_Name).ToString() + Environment.NewLine +
"Bookings: " + booking;
}
public void button2_Click(object sender, EventArgs e)
{
bool status1, status2;
string[] description;
//Error control at the outer level for valid ID
status1 = errorCheckingID();
//Proceed only if ID is valid or status1 is true
if (status1)
{
//Retrieve information from the other database. Ideally you want this method to return
//an array containing registered services. This would be an array of strings.
description = accessDB();
//Services error checking
status2 = servicesErrorCheck(description);
//Now this is the code that would call the method to save data ito database
//when status2 and 2 are true
if (status2)
{
//Code for saving into database.
DatabaseDataSet.FitnessInformationRow newRow = databaseDataSet.FitnessInformation.NewFitnessInformationRow();
newRow.Fitness_Booking_ID = databaseDataSet.FitnessInformation.Count + 1;
newRow.Description = classDescription();
newRow.MemberID = Int32.Parse(textBox3.Text);
databaseDataSet.FitnessInformation.AddFitnessInformationRow(newRow);
}
else
{
//Show error that this service is not available
MessageBox.Show("This Class is already assigned to that Member ID");
}
}
else
{
//Error message invalid ID
MessageBox.Show("Invalid ID");
}
}
private void radioButton1_Click(object sender, EventArgs e)
{
}
private void radioButton4_Click(object sender, EventArgs e)
{
}
private void radioButton3_Click(object sender, EventArgs e)
{
}
}
}
I am really not sure why this is happening so I would really appreciate any help.
You are checking each string in descriptions as follows:
serviceSeletionString.Contains(description[t].Trim())
which considering at least one of the strings is just n it will always match Spin.
Quite why you are always returning an array with the blank ones having n, I don't know. Personally I would just use a List<string> and Add each item from the database to it. But that is a separate point.
Either change it to serviceSeletionString == description[t] (don't see why you need Trim()) or just replace the whole foreach loop with description.Contains(serviceSeletionString)

Listbox Item holds data

Server 1 Server2 Server Config Screen
I am trying to make a video game server manager and I have run into an issue. I want the user to be able to have as many servers as they would like. However I cannot figure out through google searching and just regular messing around how to store the information that the user selects to become associated with the Server they create in the list. Basically when you make Server1 it takes the info you selected from the boxes on the config screen and uses them on the server selection page. But, when you make Server2, the configuration overwrites Server1's configuration. I know my code isn't even setup to be able to do this but I would appreciate a push in the right direction as to which type of code I should use.
Tl:dr I want config options to be associated with ServerX in the server list and each server should have unique settings.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string difSelect;
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if(srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
//Text being displayed to the left of the server listbox
mapLabel1.Text = mapSelect;
difLabel1.Text = difSelect;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string[] lines = { mapSelect, difSelect };
System.IO.File.WriteAllLines(#"C:\Users\mlynch\Desktop\Test\Test.txt", lines);
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
newPanel.Visible = false;
}
}
You mentioned in a recent comment that you had tried saving to a .txt file but it overwrote it anytime you tried to make an additional one. If you wanted to continue with your .txt approach, you could simply set a global integer variable and append it to each file you save.
//Variables
string srvName;
string mapSelect;
string difSelect;
int serverNumber = 0;
...
serverNumber++;
string filepath = Path.Combine(#"C:\Users\mlynch\Desktop\Test\Test", serverNumber.ToString(), ".txt");
System.IO.File.WriteAllLines(filepath, lines);
I think below source code will give you some idea about the direction. Let us start with some initializations:
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
mapBox1.Items.Add("Germany");
mapBox1.Items.Add("Russia");
difBox1.Items.Add("Easy");
difBox1.Items.Add("Difficult");
}
This is the event handler of the "Create Server" button. It takes server parameters from the screen and writes to a file named as the server.
private void crtButton_Click(object sender, EventArgs e)
{
//Add srvName to srvList
srvName = namBox1.Text;
srvList.Items.Add(srvName);
//Selections
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
//Write to config file
string path = #"C:\Test\" + srvName + ".txt";
StreamWriter sw = new StreamWriter(path);
sw.WriteLine(mapSelect);
sw.WriteLine(difSelect);
sw.Flush();
sw.Close();
//Clear newPanel form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Return to srvList
//newPanel.Visible = false;
}
And finally list box event handler is below. Method reads the server parameters from file and displays on the screen.
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
}
string path = #"C:\Test\" + srvList.SelectedItem + ".txt";
StreamReader sr = new StreamReader(path);
//Text being displayed to the left of the server listbox
mapLabel1.Text = sr.ReadLine(); // mapSelect;
difLabel1.Text = sr.ReadLine(); // difSelect;
}
Please feel free to ask any questions you have.
I ended up figuring out the issue. Basically I ended up deciding on a write to a txt file and then read from it to display the contents of the file in the server select menu. I also added a delete button so you can delete the servers that you created. it does not have full functionality yet but it is there. So here it what I ended up with and it works perfectly. Thank you all for trying to help.
public partial class Form1 : Form
{
//Variables
string srvName;
string mapSelect;
string mapFile;
string difSelect;
string difFile;
int maxPlayers;
string plrSelect;
string plrFile;
string finalFile;
string basepath = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string fileName = "config.txt";
public Form1()
{
InitializeComponent();
this.srvList.SelectedIndexChanged += new System.EventHandler(this.srvList_SelectedIndexChanged);
}
private void srvList_SelectedIndexChanged(object sender, EventArgs e)
{
//Read Server Selection
string srvSelect = srvList.GetItemText(srvList.SelectedItem);
string srvOut = System.IO.Path.Combine(basepath, srvSelect, fileName);
mapFile = File.ReadLines(srvOut).Skip(1).Take(1).First();
difFile = File.ReadLines(srvOut).Skip(2).Take(1).First();
plrFile = File.ReadLines(srvOut).Skip(3).Take(1).First();
//Display Server Selection
if (srvList.SelectedIndex == -1)
{
dltButton.Visible = false;
}
else
{
dltButton.Visible = true;
mapLabel1.Text = mapFile;
difLabel1.Text = difFile;
plrLabel1.Text = plrFile;
}
private void crtButton_Click(object sender, EventArgs e)
{
//Set Server Name
srvName = namBox1.Text;
string finalpath = System.IO.Path.Combine(basepath, srvName);
//Check if server name is taken
if (System.IO.Directory.Exists(finalpath))
{
MessageBox.Show("A Server by this name already exists");
}
else
{
//Add Server to the Server List
srvList.Items.Add(srvName);
//Server Configuration
mapSelect = mapBox1.Text;
difSelect = difBox1.Text;
maxPlayers = maxBar1.Value * 2;
plrSelect = "" + maxPlayers;
//Clear New Server Form
namBox1.Text = String.Empty;
mapBox1.SelectedIndex = -1;
difBox1.SelectedIndex = -1;
//Create the Server File
Directory.CreateDirectory(finalpath);
finalFile = System.IO.Path.Combine(finalpath, fileName);
File.Create(finalFile).Close();
//Write to config file
string[] lines = { srvName, mapSelect, difSelect, plrSelect };
System.IO.File.WriteAllLines(#finalFile, lines);
//Return to srvList
newPanel.Visible = false;
}
}
}

Update Listbox without restarting program?

I'm building an WinForms application which is going to be an adressbook. I'm stuck with a problem though. When I open the program and press on my load contacts button, it loads all that's written in the txt file. But if I create a new contact and press load again, the new contact doesn't show up. Is there any way to fix this?
Also, when I try to create new methods for example a Delete() method. It says "Items collection cannot be modified when the DataSource property is set." Any ideas why is crashes?
List<string> Load()
{
StreamReader read = new StreamReader(path);
string row = "";
while ((row = read.ReadLine()) != null)
{
adressbook.Add(row);
}
read.Close();
return adressbook; //Adressbook is my List<string> adressbook = new List<string> uptop.
}
private void button2_Click(object sender, EventArgs e)
{
List<string> list = Load();
listBox1.DataSource = list;
}
You have to set to null the DataSource before clearing and binding:
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.DataSource != null)
{
listBox1.DataSource = null;
listBox1.Items.Clear();
}
List<string> list = Load();
listBox1.DataSource = list;
}
In your Load you must first clear the list
List<string> Load()
{
if (adressbook.Count != 0)
{
adressbook.Clear();
}
StreamReader read = new StreamReader(path);
string row = "";
while ((row = read.ReadLine()) != null)
{
adressbook.Add(row);
}
read.Close();
return adressbook; //Adressbook is my List<string> adressbook = new List<string> uptop.
}

My method did not add my file into my list although no error

This is my class that after each file choose add the file to my list and from the main form raise event that update my ListBox and add the file into my ListBox.
when i am choosing 2 files i can see (with the debugger) that the add method add the first file and my list updated but after the second file pass the add method the list.count remained still 1.
public class ListboxFile
{
public delegate void OnFileAdd(string file);
public event OnFileAdd OnFileAddEvent;
private static List<string> _files;
public ListboxFile()
{
_files = new List<string>();
}
public void add(string file)
{
_files.Add(file);
OnFileAddEvent(file);
}
public void remove(string file)
{
if (_files.Contains(file))
{
_files.Remove(file);
}
}
public void clear()
{
_files.Clear();
}
public List<string> list
{
get { return _files; }
}
}
from the main form (add files button click):
private void btnAddfiles_Click(object sender, EventArgs e)
{
#region file filter
string fileToAdd = string.Empty;
System.IO.Stream stream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (lastPath.Length > 0 ? lastPath : "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net, *.pcapng, *.5vw, *.bfr, *.erf, *.tr1)" +
"|*.snoop; *.pcap; *.cap; *.net; *.pcapng; *.5vw; *.bfr; *.erf; *.tr1|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true;
thisDialog.Title = "Please Select Source File";
#endregion
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if (thisDialog.FileNames.Length > 0)
{
lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
}
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.DoWork +=
(s3, e3) =>
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((stream = thisDialog.OpenFile()) != null)
{
int numberOfFiles = thisDialog.SafeFileNames.Length;
using (stream)
{
ListboxFile lbf = new ListboxFile();
lbf.OnFileAddEvent += lbf_OnFileAddEvent;
lbf.checkFile(file);
lastPath = Path.GetDirectoryName(thisDialog.FileNames[0]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
};
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
(s3, e3) =>
{
});
backgroundWorker.RunWorkerAsync();
}
}
private void lbf_OnFileAddEvent(string file)
{
if (InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
listBoxFiles.Items.Add(file);
, listBoxFiles.Items.Count.ToString("#,##0")));
if (listBoxFiles.Items.Count != 0)
listBoxFiles.SetSelected(listBoxFiles.Items.Count - 1, true);
});
}
else
{
listBoxFiles.Items.Add(file);
if (listBoxFiles.Items.Count != 0)
listBoxFiles.SetSelected(listBoxFiles.Items.Count - 1, true);
}
}
You declare and initialize the instance of ListBoxFile inside the foreach loop.
At every loop you reinitialize the instance and thus you loose the previous add
A fast fix, move the declaration and initialization of the ListboxFile instance outside the loop (also the subscription to the event)
.....
ListboxFile lbf = new ListboxFile();
lbf.OnFileAddEvent += lbf_OnFileAddEvent;
foreach (String file in thisDialog.FileNames)
{
.....
and by the way, you call lbf.checkFile(file);, did you mean lbf.Add(file) right?
You are calling lbf.checkFile(file); but I do not see that method in your class definition. Maybe inside that method you are not firing OnFileAddEvent?

Problems submitting DataGridView changes with Linq-to-SQL

I'm trying to implement database value edition through a DataGridView control but honestly I'm having a hard time trying to accomplish that. I'm basically using LINQ-to-SQL classes and events, the following being the most significant snippets:
var data = from q in data.FOOBARS
select new
{
ID = q.FOOBAR_ID,
LOREM = q.FOOBAR_LOREM,
IPSUM = q.FOOBAR_IPSUM
};
DataGridView grid = new DataGridView();
grid.DataSource = data;
// grid EVENTS
private void grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
this.grid.CurrentCell.ReadOnly = false;
this.grid.BeginEdit(true);
}
private void grid_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (this.grid.CurrentCell.IsInEditMode)
{
// METHOD CALL
this.SetVariableValue(this.grid.CurrentRow.Cells["ID"].Value.ToString(), this.grid.CurrentCell.OwningColumn.Name, this.grid.CurrentCell.FormattedValue.ToString(), this.grid.CurrentCell.EditedFormattedValue.ToString());
}
this.grid.CommitEdit(DataGridViewDataErrorContexts.Commit);
this.grid.EndEdit();
}
// METHOD IMPL
private void SetVariableValue(string id, string type, string current, string edited)
{
try
{
if (current != edited)
{
using (FOOBARDataClassesDataContext data = new FOOBARDataClassesDataContext(this.BuildConnection()))
{
data.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
switch (type)
{
case "LOREM":
var currentLorem = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id)).FOOBAR_LOREM;
currentLorem = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);
break;
case "IPSUM":
var currentIpsum = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id)).FOOBAR_IPSUM;
currentIpsum = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);
break;
default:
break;
}
data.Refresh(RefreshMode.OverwriteCurrentValues);
}
}
}
catch (Exception error)
{
if (logger.IsErrorEnabled) logger.Error(error.Message);
}
}
Debugging looks good, objects are actually being updated but for some reason changes are neither being submitted nor updated.
Any help would be certainly appreciated. Thanks much you guys in advance!
For some reason this does NOT WORK:
var currentLorem = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id)).FOOBAR_LOREM;
currentLorem = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);
But this DOES (notice the changes in lines 1 and 2, FOOBAR_LOREM attribute):
var currentLorem = data.FOOBARS.SingleOrDefault(v => v.FOOBAR_ID == Convert.ToInt32(id));
currentLorem.FOOBAR_LOREM = edited;
data.SubmitChanges(ConflictMode.ContinueOnConflict);

Categories