I am working on an csv changing tool for magento.
This tool has to change some values of a csv file.
I have already imported the csv into a gridview.
My question is how do you Read a value of a single cell and change it from a gridview.
I am using the windows form c#
i want something like this:
imput:
EAN,Product code,name
363738492,MT-01234,iphone case
153289234,MT-89854,samsung case
876253483,PO-43466,network cable
output:
EAN,sku,name
363738492,MT-01234,iphone case
153289234,MT-89854,samsung case
876253483,PO-43466,network cable
this is my working import code:
private void Import_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = #"c:\";
fdlg.FileName = txtFileName.Text;
fdlg.Filter = "Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
txtFileName.Text = fdlg.FileName;
Import();
Application.DoEvents();
}
}
public static DataTable GetDataTable(string strFileName)
{
ADODB.Connection oConn = new ADODB.Connection();
oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";", "", "", 0);
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
ADODB.Recordset rs = new ADODB.Recordset();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
DataTable dt = new DataTable();
rs.Open(strQuery, "Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\";",
ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly, 1);
adapter.Fill(dt, rs);
return dt;
}
private void Import()
{
if (txtFileName.Text.Trim() != string.Empty)
{
try
{
DataTable dt = GetDataTable(txtFileName.Text);
dgvGv.DataSource = dt.DefaultView;
dgvGv2.DataSource = dt.DefaultView;
dgvGv3.DataSource = dt.DefaultView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
this is my working export code:
private void button1_Click(object sender, EventArgs e)
{
// Don't save if no data is returned
if (dgvGv.Rows.Count == 0)
{
return;
}
StringBuilder sb = new StringBuilder();
// Column headers
string columnsHeader = "";
for (int i = 0; i < dgvGv.Columns.Count; i++)
{
columnsHeader += dgvGv.Columns[i].Name + ",";
}
sb.Append(columnsHeader + Environment.NewLine);
// Go through each cell in the datagridview
foreach (DataGridViewRow dgvRow in dgvGv.Rows)
{
// Make sure it's not an empty row.
if (!dgvRow.IsNewRow)
{
for (int c = 0; c < dgvRow.Cells.Count; c++)
{
// Append the cells data followed by a comma to delimit.
sb.Append(dgvRow.Cells[c].Value + ",");
}
// Add a new line in the text file.
sb.Append(Environment.NewLine);
}
}
// Load up the save file dialog with the default option as saving as a .csv file.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV files (*.csv)|*.csv";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// If they've selected a save location...
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
{
// Write the stringbuilder text to the the file.
sw.WriteLine(sb.ToString());
}
}
// Confirm to the user it has been completed.
MessageBox.Show("CSV file saved.");
}
feel free to comment for any questions.
/Select CSV File from drop down then click Import from /In Button Clink Event
private void btnimportexcel_Click(object sender, EventArgs e)
{
string source = string.Empty;
source = cmbImportsource.Text;
if (!string.IsNullOrEmpty(source ))
{
string smsfilename=string .Empty ;
OpenFileDialog of = new OpenFileDialog();
DialogResult dlresult;
of.InitialDirectory = Environment.SpecialFolder.Desktop.ToString ();
switch (source)
{
case "EXCEL":
of.Filter = "Excel File(*.xlsx,*.xls)|*.xlsx;*.xls|All Files(*.*)|*.*";
of.Title = "Select Excel File...";
dlresult = of.ShowDialog();
if (dlresult == DialogResult.OK )
{
smsfilename = of.FileName;
if (System.IO.File.Exists(smsfilename))
{
getRecordFromXcel(smsfilename);
}
}
break;
case "CSV":
//"Text and CSV Files(*.txt, *.csv)|*.txt;*.csv|Text Files(*.txt)|*.txt|CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
of.Filter = "CSV Files(*.csv)|*.csv|All Files(*.*)|*.*";
of.Title = "Select Excel File...";
dlresult = of.ShowDialog();
if (dlresult == DialogResult.OK )
{
smsfilename = of.FileName;
if (System.IO.File.Exists(smsfilename))
{
getRecordFromCSV(smsfilename);
}
}
break;
case "TEXT FILE":
break;
}
}
//When File Selected
private void getRecordFromCSV(string file)
{
String textLine = string.Empty;
String[] splitLine;
bool columncreater = false;
try
{
StreamReader objReaders = new StreamReader(file);
dataGridView1.DataSource = null;
dataGridView1.Columns.Clear();
dataGridView1.Rows.Clear();
int datagridrowindex =-1;
do
{
textLine = objReaders.ReadLine();
datagridrowindex= datagridrowindex + 1;
if (textLine != "")
{
splitLine = textLine.Split(',');
//if (splitLine[0] != "" || splitLine[1] != "")
//{
// dataGridView1.Rows.Add(splitLine[0]);
//}
if (columncreater ==false )
{
for (int i = 0; i < splitLine.Length; i++)
{
dataGridView1.Columns.Add("C" + i + "", "C" + i + "");
}
columncreater = true;
}
dataGridView1.Rows.Add(splitLine);
int cc = dataGridView1.Columns.Count;
int rr = dataGridView1.Rows.Count;
}
} while (objReaders.Peek() != -1);
}
catch (Exception ex)
{
}
}
Related
I'm currently adding data to my dataGridView1 using the Form1_Load load event. Now I'm trying to add more data from a textfile which im loading into the winforms application.
As you guys will see, I'm trying to add more rows into the dataGridView1 but those new rows wont be added. What am I doing wrong?
I appreciate any kind of suggestions and help.
getTexFilePath function code:
private void getTexFilePath()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
foreach (var line in File.ReadAllLines(filePath))
{
var index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["Column1"].Value = line;
dataGridView1.Rows[index].Cells["Column2"].Value = "undefined";
}
}
}
Form1_Load code:
private void Form1_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Username", typeof(string));
table.Columns.Add("Links");
table.Rows.Add("No File uploaded", "Missing data");
dataGridView1.DataSource = table;
}
Not knowing all of your requirements, this would be where I'd start.
using System.ComponentModel;
using System.Windows.Forms;
using System.IO;
namespace DatagridView_AddRowsAfterInitialLoad_45922121
{
public partial class Form1 : Form
{
string filePath = "";
BindingList<dgventry> dgvSourceList = new BindingList<dgventry>();
public Form1()
{
InitializeComponent();
InitializeDGV();
//put initial values in the grid
dgvSourceList.Add(new dgventry { field1 = "yeah", field2 = "yeah in f2", field3 = "yeah in F3" });
//put values from the datafile
getTexFilePath();
}
private void InitializeDGV()
{
dataGridView1.DataSource = dgvSourceList;
}
private void getTexFilePath()
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = #"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
foreach (var line in File.ReadAllLines(filePath))
{
dgvSourceList.Add(new dgventry { field1 = line, field2 = "", field3 = "" });
}
}
}
}
public class dgventry
{
public string field1 { get; set; }
public string field2 { get; set; }
public string field3 { get; set; }
}
}
In Form1_Load you use a data source (DataTable instance) so your grid is data bound (means, the grid reflects the content of its source).
However, in getTexFilePath you just try to add rows to the grid itself in an unbound manner.
Solution 1
You should add new lines to your underlying DataTable instead.
Solution 2
Create a new table and reset the binding:
dataGridView1.DataSource = null;
DataTable newDataTable = ReadFileAsDataTable(fileName); // implement this
dataGridView1.DataSource = newDataTable;
Solution 3
Use a non-bound grid also in Load event, similarly to your getTexFilePath. But this is not recommended because in this case you do not have a clean UI independent model object (data source), and you can read business data only from the UI control, which is nasty.
The easy way to deal with this is to have your DataTable table as a member of your form class. So in Form_Load you just have:
table = new DataTable();
Then in your foreach loop in GetTexFilePath use the following:
DataRow dR = table.NewRow();
dR[0] = line;
dR[1] = "undefined";
table.rows.Add(dR);
I have a code that let user select the files and load the data in the text files to datagridview.
private void cmdload_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Point");
table.Columns.Add("X");
table.Columns.Add("Y");
table.Columns.Add("Z");
table.Columns.Add("R");
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "\\Yamaha";
openFileDialog1.Filter = "Data Files (*.PNT)|*.PNT";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
using (var reader = File.OpenText(#filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
}
dataGridView1.DataSource = table;
}
}
}
}
EDITED:
I have edited my code as suggested but the value just doesn't display. Please advise.
private void cmdload_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Point");
table.Columns.Add("X");
table.Columns.Add("Y");
table.Columns.Add("Z");
table.Columns.Add("R");
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "Data Files (*.PNT)|*.PNT";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
using (var reader = File.OpenText(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
}
dataGridView1.DataSource = table;
}
}
}
}
catch (Exception ex) // you need to add the catch block if yo are using try block
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
The text file looks like :
I want the data files to be paste in the gridview when user load the files.
Now i not sure why my code doesnt work. Can anyone give me an advise please?
please have a look :
private void cmdload_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Point");
table.Columns.Add("X");
table.Columns.Add("Y");
table.Columns.Add("Z");
table.Columns.Add("R");
table.Columns.Add("A");
table.Columns.Add("B");
table.Columns.Add("C");
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "C:\\"; // your directory is also not defined properly
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";// have a look to filter as well
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
string filename = openFileDialog1.FileName;
using (var reader = File.OpenText(filename)) // you need not to use '#filename' instead use just 'filename'
{
string line;
while ((line = reader.ReadLine()) != null)
{
string[] parts = line.Split(' ');
table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7]);
}
dataGridView1.DataSource = table;
}
}
}
}
catch (Exception ex) // you need to add the catch block if yo are using try block
{
}
}
hope it helps.
it doest work:<, here is my code:
public void buttonSaveTo_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
richTextBox1.Text = fbd.SelectedPath;
string destination = fbd.SelectedPath;
}
and this is how i try to save files
{
webClient.DownloadFile("http://i.imgur.com/" + picture, #"destionation" + picture);
}
EDIT// okay thanks for answers but it still doesnt work:<, maybe im doing omething wrong, look this is all code i wrote
namespace Imgur
{
public partial class Form1 : Form
{
bool flag = true;
int downloadedNumber = 0;
public Form1()
{
InitializeComponent();
}
public void buttonStart_Click(object sender, EventArgs e)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
if (!flag)
{
flag = true;
}
for (int i=0;i<100000 && flag;i++)
{
WebClient webClient = new WebClient();
string pic1 = rnd_str(5);
string pic2 = ".jpg";
string picture = pic1 + pic2;
//********** GETTING SIZE OF IMAGE ***********
Size sz = GetSize("http://i.imgur.com/" + picture);
string imageSize = (sz.Width.ToString() + " " + sz.Height.ToString()); ;
//********************************************
if(imageSize != "161 81")
{
webClient.DownloadFile("http://i.imgur.com/" + picture, destination + picture);
richTextBox1.Text += String.Format("Downloaded picture: {0}\r\n", picture);
downloadedNumber++;
textBoxDownloadedNumber.Text = string.Format("{0}", downloadedNumber);
}
webClient.Dispose();
Application.DoEvents();
if (i == 999995)
{
flag = false;
}
}
richTextBox1.Text += "theend\n";
buttonStart.Enabled = true;
buttonStop.Enabled = false;
}
public static Size GetSize(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.Accept = "image/gif";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
Bitmap bmp = new Bitmap(s);
Size sz = new Size(bmp.Width, bmp.Height);
return sz;
}
public static string rnd_str(int liczba_liter)
{
Random r = new Random();
int char_type;
string return_string = "";
int i =0;
for (i = 0; i < liczba_liter; i++)
{
if (r.Next(1, 3) == 1)
{
char_type = r.Next(1, 4);
switch (char_type)
{
case 1:
return_string += (char)r.Next(48, 58); // convertion int -> ASCII character; 48-57 are ASCII digits
break;
case 2:
return_string += (char)r.Next(97, 123); // convertion int -> ASCII character; as above but small letters
break;
case 3:
return_string += (char)r.Next(65, 91); // as above; large letters
break;
default:
i -= 1;
break;//do not add any letter if no type is allowed
}
}
else
{
i -= 1;
return_string += "";
}
}
return return_string;
}
private void buttonStop_Click(object sender, EventArgs e)
{
flag = false;
buttonStart.Enabled = true;
}
public void buttonSaveTo_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
richTextBox1.Text = fbd.SelectedPath;
string destination = fbd.SelectedPath;
}
}
}
You are currently just concatenating strings, but your folder name probably does not end with a directory separator char. Assuming picture is the file name of your picture (e.g. foo.jpg) use Path.Combine() instead to let the framework do the work for you:
var localFileName = Path.Combine(destination, picture);
webClient.DownloadFile("http://i.imgur.com/" + picture, localFileName);
Your "destination" in the DownloadFile-Call is a string and not the actual variable. Also the destination variable must be on class level. SOmthing like:
private string destination;
public void buttonSaveTo_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.ShowDialog();
richTextBox1.Text = fbd.SelectedPath;
destination = fbd.SelectedPath;
}
webClient.DownloadFile("http://i.imgur.com/" + picture, System.IO.Path.Combine(destionation, picture));
I have the following program that will send (output) information to a text file, but now I want to read (input) from the text file. Any suggestions would be greatly appreciated. I have commented out a couple of things that "I think" I need to do; but I am not really certain how to proceed.
using System.Windows.Forms;
using System.IO;
namespace Input_Output
{
public partial class Grades : Form
{
private StreamWriter output;
private StreamReader input;
public Grades()
{
InitializeComponent();
}
private void label4_Click(object sender, EventArgs e)
{
}
private void btnCreate_Click(object sender, EventArgs e)
{
btnEnter.Visible = true;
btnClose.Visible = true;
txtFirst.Visible = true;
txtLast.Visible = true;
lblFirst.Visible = true;
lblLast.Visible = true;
listBox1.Visible = true;
lblStatus.Visible = true;
lblGrade.Visible = true;
lblCourse.Visible = true;
cmbID.Visible = true;
lblID.Visible = true;
txtCourse.Visible = true;
txtGrade.Visible = true;
lblStatus.Visible = true;
DialogResult result;
string fileName;
using (SaveFileDialog chooser = new SaveFileDialog())
{
result = chooser.ShowDialog();
fileName = chooser.FileName;
}
output = new StreamWriter(fileName);
btnCreate.Enabled = false;
txtFirst.Visible = true;
txtLast.Visible = true;
lblFirst.Visible = true;
lblLast.Visible = true;
btnEnter.Visible = true;
btnClose.Visible = true;
}
private void btnClose_Click(object sender, EventArgs e)
{
//Close button pushes information from the listbox in to the text file
output.Close();
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Output File";
btnCreate.Enabled = true;
listBox1.Items.Clear();
cmbID.Text = "";
}
private void btnEnter_Click(object sender, EventArgs e)
{
// Enter button sends information to the list box, a Message Box prompts user to check for accuracy.
//Close button pushes information to the Text file.
string last = "";
string first = "";
string course = "";
string grade = "";
if (txtFirst.Text != "" && txtLast.Text != "" && txtCourse.Text != "")
{
last = txtFirst.Text;
first = txtLast.Text;
course = txtCourse.Text;
grade = txtGrade.Text;
output.WriteLine (last + "\t"+ "\t" + first + ":"+ "\t" + cmbID.SelectedItem + "_" + course + "_" + grade );
listBox1.Items.Add(txtLast.Text + "," + txtFirst.Text + ":" + cmbID.SelectedItem + "-" + txtCourse.Text + "-" + txtGrade.Text);
lblStatus.ForeColor = Color.Navy;
lblStatus.Text = "Entry Saved";
txtFirst.Text = "";
txtLast.Text = "";
txtCourse.Text = "";
txtGrade.Text = "";
txtFirst.Focus();
}
else
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = "Empty text box or boxes";
}
MessageBox.Show("Please verify that the information is correct before proceeding");
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Grades_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult result;
string fileName;
using (OpenFileDialog chooser = new OpenFileDialog())
{
result = chooser.ShowDialog();
fileName = chooser.FileName;
}
//while loop?
//if variable is null, it's the end of the record
//variable= !null
//txt read int variable TxtFile.Text += Rec + "\r\n"; while rec !=null;
}
}
}
To read a text file one line at a time you can do like this:
using System.IO;
using (var reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Do stuff with your line here, it will be called for each
// line of text in your file.
}
}
There are other ways as well. For example, if the file isn't too big and you just want everything read to a single string, you can use File.ReadAllText()
myTextBox.Text = File.ReadAllText(fileName);
It's just one line of code:
string content = System.IO.File.ReadAllText(#"C:\textfile.txt");
Try this:
if(result == DialogResult.OK && fileName != null)
{
try
{
var fileText=File.ReadAllText(fileName);
}
catch(Exception ex)
{
//Handle exception here
}
}
It will read all the data from the selected file into the fileText variable.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace part_B_19
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
StreamReader sr = new StreamReader(#"C:\Users\Acer\Documents\Visual Studio 2012\Projects\combobox.txt");
string line = sr.ReadLine();
while (line != null)
{
comboBox1.Items.Add(line);
line = sr.ReadLine();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Sample program demonstrating FILE i/o in C#
class Items
{
public int itemID { get; set; }
public string itemName { get; set; }
public int itemNo { get; set; }
public string pkgdate { get; set; }
}
class Program
{
private static string connectionString = "...";
static void Main(string[] args)
{
string streadpath = #"I:\itemdata.txt";
string stwritepath = #"I:\itemdata1.txt";
string stcopypath = #"I:\itemdata2.txt";
List<Items> li_all = new List<Items>();
List<Items> li_db = new List<Items>();
List<Items> li_valid = new List<Items>();
List<Items> li_invalid = new List<Items>();
li_all = stread_file(streadpath);
li_invalid = validate(li_all);
li_db = retrievefromDB();
bool x = stwrite_invalid(li_db, stwritepath);
bool y = stcopy_file(streadpath, stcopypath);
}
static List<Items> stread_file(string stpath)
{
List<Items> stli = new List<Items>();
using (StreamReader SR = new StreamReader(stpath))
{
string line = "";
while ((line = SR.ReadLine()) != null)
{
string[] linevalues = line.Split(',');
Items obj = new Items();
obj.itemID = int.Parse(linevalues[0]);
obj.itemName = linevalues[1];
obj.itemNo = int.Parse(linevalues[2]);
obj.pkgdate = linevalues[3];
stli.Add(obj);
}
}
return stli;
}
static List<Items> validate(List<Items> stli)
{
List<Items> li_valid = new List<Items>();
List<Items> li_invalid = new List<Items>();
DateTime parsed;
foreach (Items stit in stli)
{
if(DateTime.TryParseExact(stit.pkgdate, "MM/dd/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None, out parsed))
{
li_valid.Add(stit);
}
else
{
li_invalid.Add(stit);
}
}
InsertDataToDb(li_valid);
return li_invalid;
}
static bool stwrite_invalid(List<Items> stli,string stpath)
{
using (StreamWriter SW = new StreamWriter(stpath))
{
foreach(Items stit in stli)
{
SW.WriteLine(stit.itemID + "," + stit.itemName + "," + stit.itemNo + "," + stit.pkgdate);
}
}
return true;
}
static bool stcopy_file(string stsourcepath, string stdestinationpath)
{
File.Copy(stsourcepath, stdestinationpath);
return true;
}
static void InsertDataToDb(List<Items> stli)
{
var records = stli;
using (SqlConnection con = new SqlConnection(connectionString))
{
StringBuilder nonQuery = new StringBuilder();
foreach (var item in records)
{
nonQuery.AppendFormat("INSERT INTO dbo.Smartphone VALUES ({0}, '{1}', {2}, '{3}');",
item.itemID,
item.itemName,
item.itemNo,
item.pkgdate);
}
SqlCommand cmd = new SqlCommand(nonQuery.ToString(),con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
static List<Items> retrievefromDB()
{
List<Items> stli = new List<Items>();
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from dbo.Smartphone", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Items obj = new Items();
obj.itemID = (int)dt.Rows[i]["ID"];
obj.itemName = dt.Rows[i]["Name"].ToString();
obj.itemNo = (int)dt.Rows[i]["Num"];
obj.pkgdate = dt.Rows[i]["RDate"].ToString();
stli.Add(obj);
}
}
return stli;
}
}
namespace CDKatalog
{
public partial class KorisnickoUputstvo : System.Web.UI.Page
{
string[] izvodjac = new string[20];
string[] nazivAlbuma = new string[20];
string[] zanr = new string[20];
string[] godinaIzdavanja = new string[20];
string[] izdavackaKuca = new string[20];
string[] slikaOmota = new string[20];
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1990; i <= 2019; i++)
{
DropDownList2.Items.Add(i.ToString());
}
StreamReader sr = File.OpenText(Server.MapPath(#"\textFajl\katalog.txt"));
string sadrzaj = sr.ReadToEnd();
int brojac = 1;
int j = 0;
for (int i = 0; i < sadrzaj.Length; i++)
{
if (sadrzaj[i] == '^') { j++; brojac++; }
else if (sadrzaj[i] == '|')
{
brojac++;
}
else if (brojac % 6 == 1)
{
izvodjac[j] = izvodjac[j] + sadrzaj[i];
}
else if (brojac % 6 == 2)
{
nazivAlbuma[j] = nazivAlbuma[j] + sadrzaj[i];
}
else if (brojac % 6 == 3)
{
zanr[j] = zanr[j] + sadrzaj[i];
}
else if (brojac % 6 == 4)
{
godinaIzdavanja[j] = godinaIzdavanja[j] + sadrzaj[i];
}
else if (brojac % 6 == 5)
{
izdavackaKuca[j] = izdavackaKuca[j] + sadrzaj[i];
}
else if (brojac % 6 == 0)
{
slikaOmota[j] = slikaOmota[j] + sadrzaj[i];
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
string pomoc = "";
for (int i = 1; i < 7; i++)//OVDE TREBA MENJATI BROJ
{
for (int c = 0; c < TextBox1.Text.Length; c++)
{
if (TextBox1.Text[c] == izvodjac[i][c + 2])
{
pomoc = pomoc + TextBox1.Text[c];
}
else {
pomoc = "";
break;
}
}
if (pomoc != "")
{
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
}
Label1.Text = nazivAlbuma[1][1].ToString();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
string pomoc = "";
for (int i = 1; i < 7; i++)
{
for (int c = 0; c < TextBox2.Text.Length; c++)
{
if (TextBox2.Text[c] == nazivAlbuma[i][c])
{
pomoc = pomoc + TextBox2.Text[c];
}
else
{
pomoc = "";
break;
}
}
if (pomoc != "")
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button5_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("GodinaIzdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
string pomoc = "";
for (int i = 1; i < 7; i++)
{
for (int c = 0; c < TextBox3.Text.Length; c++)
{
if (TextBox3.Text[c] == izdavackaKuca[i][c])
{
pomoc = pomoc + TextBox3.Text[c];
}
else
{
pomoc = "";
break;
}
}
if (pomoc != "")
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button3_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("Naziv Albuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
for (int i = 0; i < 7; i++)
{
if (DropDownList1.SelectedValue == zanr[i]) {
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Button4_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Izvodjac", typeof(string));
dt.Columns.Add("NazivAlbuma", typeof(string));
dt.Columns.Add("Zanr", typeof(string));
dt.Columns.Add("Godina Izdavanja", typeof(string));
dt.Columns.Add("Izdavacka Kuca", typeof(string));
for (int i = 0; i < 7; i++)
{
if (DropDownList2.SelectedValue == godinaIzdavanja[i])
{
dt.Rows.Add(izvodjac[i], nazivAlbuma[i], zanr[i], godinaIzdavanja[i], izdavackaKuca[i]);
}
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Use Split() like in the code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"C:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string inputLine = "";
List<List<int>> data = new List<List<int>>();
while ((inputLine = reader.ReadLine()) != null)
{
string[] inputArray = inputLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (inputArray.Count() > 0)
{
List<int> numbers = inputArray.Select(x => int.Parse(x)).ToList();
data.Add(numbers);
}
}
}
}
}
Check this code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
'openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 1
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
dataFile = openFileDialog1.FileName
Label1.Text = openFileDialog1.SafeFileName
Dim myReader As New StreamReader(dataFile)
Dim line As String
line = myReader.ReadLine()
While Not (line Is Nothing)
Dim str() As String = Split(line, ControlChars.Tab)
ListView1.Items.Add(New ListViewItem(str))
line = myReader.ReadLine()
End While
myReader.Close()
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
I've taken over somebody's program. So this is my first time dealing with DataViewGrid.
The data populates perfectly. When the user select a row it populates a text box in the form. Which I'm not sure how that part is working since there is nothing that says
txtEmail.text =
Or Selected Row anywhere in this form. But it's ok.. if it works I'll deal.
Here's my issue. I've added a filter. which works great. As you type it filters each row for the matches.
private void txtSearch_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
dv.Sort = "Name ASC";
dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
dataGridView1.DataSource = dv;
}
But now as soon as you type anything in the filter, any row that is selected does not populate the textbox. It isn't until I reload the entire form that I can select anything properly again.
If I'm beginning to understand... I've update the gridview but not the source.. I just don't know how.
Thanks!
-Matt
Whole Form
In the designer view I have 3 text boxes. txtEmail, txtName, txtImageCount that get populated as I make a new selection. But once I filter the datagridview the boxes never get populated as I try to select rows.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using Ini;
using System.Configuration;
using System.Threading;
namespace UpLoadImages
{
public partial class CopyFavorites : Form
{
public CopyFavorites()
{
InitializeComponent();
}
private void CopyFavorites_Load(object sender, EventArgs e)
{
try
{
// get the default values
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
IniFile ini = new IniFile(string.Format(#"{0}\gift.ini", appPath));
txtEventsDrive.Text = ini.IniReadValue("Info", "LocationOfEvents");
txtHiResTarget.Text = ini.IniReadValue("Info", "FavWorkSpace");
this.StartPosition = FormStartPosition.CenterScreen;
oleDbConnection1.ConnectionString = ConfigurationSettings.AppSettings["ConnectionString"];
backgroundWorker1.RunWorkerAsync();
//commented out so we can try it as a background worker
// TODO: This line of code loads data into the 'dsFavoritesList.gryFavoritesList' table. You can move, or remove it, as needed.
//this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);
ProgressPanel.Visible = false;
txtSearch.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnCopy_Click(object sender, EventArgs e)
{
this.MdiParent.MainMenuStrip.Enabled = false;
try
{
string strError = CopyImages();
StringBuilder sql = new StringBuilder();
sql.AppendFormat("UPDATE FavoritesHeader SET FavoritesHeader.FilesCopied = {0} ", Convert.ToInt32(txtImagesCopied.Text));
sql.AppendFormat("WHERE FavoritesHeader.EmailAddress='{0}'", txtEmail.Text);
UpdateDatabase(sql.ToString());
this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(this, strError, "Copy Images", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
ProgressPanel.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.MdiParent.MainMenuStrip.Enabled = true;
}
}
private string CopyAllImages()
{
StringBuilder strError = new StringBuilder();
string clr = "\r\n";
strError.AppendFormat("Time started: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);
try
{
StringBuilder str = new StringBuilder();
str.AppendFormat("Select FavoritesHeader.EmailAddress, StrConv([LastName],1)+'_'+StrConv([firstname],3) AS Folder, FavoritesDetail.ImagePath,MainEvents.MainEventCode, ");
str.AppendFormat("FavoritesDetail.ImageName FROM (FavoritesHeader INNER JOIN MainEvents ON FavoritesHeader.MainEventID = MainEvents.MainEventID) ");
str.AppendFormat("LEFT JOIN FavoritesDetail ON FavoritesHeader.FavoritesHeaderID = FavoritesDetail.FavoritesHeaderID ");
str.AppendFormat(" WHERE (((MainEvents.isActive)=1)) ");
str.AppendFormat(" ORDER BY FavoritesHeader.EmailAddress, StrConv([LastName],1)+'_'+StrConv([firstname],3), FavoritesDetail.ImagePath");
DataTable dt_Images = GetDataTable(str.ToString());
int maxFiles = dt_Images.Rows.Count;
strError.AppendFormat("Images to copy: {0}{1}{1}", maxFiles, clr);
Application.DoEvents();
progressBar.Maximum = maxFiles;
progressBar.Value = 0;
ProgressPanel.Visible = true;
string strTarget = string.Empty;
int i = 0;
foreach (DataRow row in dt_Images.Rows)
{
i = i + 1;
progressBar.Value = i;
ProgressCount.Text = string.Format("Files Copied: {0} of {1}", i, maxFiles);
Application.DoEvents();
string path = row["ImagePath"] as string;
path = path.Replace(#"Thumbs", #"Preview");
//string folder = row["Folder"].ToString().Replace("#", "_").Replace(".", "_");
string folder = row["Folder"].ToString();//.Replace("#", "_").Replace(".", "_");
strTarget = string.Format(#"{0}\Favorites_{1}\{2}", txtHiResTarget.Text, row["MainEventCode"] as string, folder);
if (!System.IO.Directory.Exists(strTarget))
{
// create the directory
System.IO.Directory.CreateDirectory(strTarget);
}
string destFileName = string.Format(#"{0}\{1}", strTarget, row["ImageName"] as string);
string sourceFileName = string.Format(#"{0}\{1}", txtEventsDrive.Text, path);
sourceFileName = sourceFileName.Replace(#"/", #"\");
sourceFileName = sourceFileName.Replace(#"\\", #"\");
try
{
System.IO.File.Copy(sourceFileName, destFileName,true);
}
catch (Exception ex)
{
strError.AppendFormat("{0}{1}{1}", ex.Message, clr);
}
}
//DirectoryInfo dir3 = new DirectoryInfo(strTarget);
//txtImagesCopied.Text = Convert.ToString(dir3.GetFiles("*.jpg").Length);
//strError.AppendFormat("Images in destination: {0}{1}{1}", txtImagesCopied.Text, clr);
strError.AppendFormat("Time Ended: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return strError.ToString();
}
private string CopyImages()
{
StringBuilder strError = new StringBuilder();
string clr = "\r\n";
strError.AppendFormat("Time started: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);
try
{
StringBuilder str = new StringBuilder();
str.AppendFormat("SELECT FavoritesHeader.EmailAddress, MainEvents.MainEventCode, FavoritesDetail.ImagePath, ");
str.AppendFormat("FavoritesDetail.ImageName FROM (FavoritesHeader LEFT JOIN FavoritesDetail ON ");
str.AppendFormat("FavoritesHeader.FavoritesHeaderID = FavoritesDetail.FavoritesHeaderID) INNER JOIN ");
str.AppendFormat(" MainEvents ON FavoritesHeader.MainEventID = MainEvents.MainEventID WHERE ");
str.AppendFormat(" FavoritesHeader.EmailAddress='{0}' AND MainEvents.isActive=1", txtEmail.Text);
DataTable dt_Images = GetDataTable(str.ToString());
int maxFiles = dt_Images.Rows.Count;
strError.AppendFormat("Images to copy: {0}{1}{1}", maxFiles, clr);
Application.DoEvents();
progressBar.Maximum = maxFiles;
progressBar.Value = 0;
ProgressPanel.Visible = true;
string strTarget = string.Empty;
int i = 0;
int AlreadyExists = -1;
int ExistsIndex = 0;
foreach (DataRow row in dt_Images.Rows)
{
i = i + 1;
progressBar.Value = i;
ProgressCount.Text = string.Format("Files Copied: {0} of {1}", i, maxFiles);
Application.DoEvents();
string path = row["ImagePath"] as string;
path = path.Replace(#"Thumbs", #"HiRes");
string eMail = txtEmail.Text.ToString().Replace("#", "_").Replace(".", "_");
strTarget = string.Format(#"{0}\{1}_MainEvent\FavoriteCD\{2}", txtHiResTarget.Text, row["MainEventCode"] as string, eMail);
if (!System.IO.Directory.Exists(strTarget))
{
// create the directory
System.IO.Directory.CreateDirectory(strTarget);
}
string destFileName = string.Format(#"{0}\{1}", strTarget, row["ImageName"] as string);
string sourceFileName = string.Format(#"{0}\{1}", txtEventsDrive.Text, path);
sourceFileName = sourceFileName.Replace(#"/", #"\");
//sourceFileName = sourceFileName.Replace(#"\\", #"\");
try
{
System.IO.File.Copy(sourceFileName, destFileName);
}
catch (Exception ex)
{
AlreadyExists = (strError.ToString()).IndexOf("already exists");
if (AlreadyExists == -1)
{
strError.AppendFormat("{0}{1}{1}", ex.Message, clr);
}
else
{
ExistsIndex = ExistsIndex + AlreadyExists;
}
}
}
if (ExistsIndex > 0)
{
strError.AppendFormat("Some files were copied previously{0}", clr);
}
DirectoryInfo dir3 = new DirectoryInfo(strTarget);
txtImagesCopied.Text = Convert.ToString(dir3.GetFiles("*.jpg").Length);
strError.AppendFormat("Images in destination: {0}{1}{1}", txtImagesCopied.Text, clr);
strError.AppendFormat("Time Ended: {0}{1}{1}", DateTime.Now.ToLongTimeString(), clr);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return strError.ToString();
}
private void UpdateDatabase(string sql)
{
OleDbConnection sqlConnNew = new OleDbConnection();
sqlConnNew.ConnectionString = oleDbConnection1.ConnectionString;
sqlConnNew.Open();
OleDbCommand oleCMD = new OleDbCommand();
oleCMD.Connection = sqlConnNew;
OleDbTransaction oleTrans = oleCMD.Connection.BeginTransaction();
oleCMD.Transaction = oleTrans;
oleCMD.CommandText = sql;
try
{
oleCMD.ExecuteNonQuery();
oleTrans.Commit();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
oleCMD.Connection.Close();
oleCMD.Dispose();
}
public DataTable GetDataTable(string sql)
{
DataTable RS = new DataTable();
try
{
OleDbConnection sqlConnNew = new OleDbConnection();
sqlConnNew.ConnectionString = oleDbConnection1.ConnectionString;
sqlConnNew.Open();
OleDbCommand oleCMD = new OleDbCommand(sql, sqlConnNew);
OleDbDataAdapter oleAdr = new OleDbDataAdapter(oleCMD);
oleAdr.AcceptChangesDuringFill = true;
oleAdr.Fill(RS);
oleCMD.Connection.Close();
oleCMD.Dispose();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
return RS;
}
private void SaveDefaults_Click(object sender, EventArgs e)
{
try
{
// get the application path to find the ini file
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
IniFile ini = new IniFile(string.Format(#"{0}\gift.ini", appPath));
ini.IniWriteValue("Info", "LocationOfEvents", txtEventsDrive.Text);
ini.IniWriteValue("Info", "FavWorkSpace", txtHiResTarget.Text);
MessageBox.Show("Defaults settings have been saved.", "Save Defaults");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Exit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void About_Click(object sender, EventArgs e)
{
AboutBox MyAboutBox = new AboutBox();
MyAboutBox.ShowDialog();
}
private void getInvoiceToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
GetInvoice getInvoice = new GetInvoice();
getInvoice.ShowDialog();
}
private void processImagesToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Hide();
ProcessImages processImages = new ProcessImages();
processImages.ShowDialog();
}
private void btnRefresh_Click(object sender, EventArgs e)
{
lblLoadingData.Visible = true;
this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);
dataGridView1.Refresh();
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
dv.Sort = "Name ASC";
dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
dataGridView1.DataSource = dv;
//if (index == -1)
//{
// MessageBox.Show("No PK matches " + txtSearch.Text);
//}
//else
//{
// dataGridView1.FirstDisplayedScrollingRowIndex = index;
// dataGridView1.Refresh();
// dataGridView1.CurrentCell = dataGrid.Rows[index].Cells[0];
// dataGridView1.Rows[index].Selected = true;
//dataGridView1.CurrentRowIndex = intRow;
//dataGridView1.Select(intRow);
//}
}
private void btnExport_Click(object sender, EventArgs e)
{
this.MdiParent.MainMenuStrip.Enabled = false;
try
{
string strError = CopyAllImages();
MessageBoxButtons buttons = MessageBoxButtons.OK;
MessageBox.Show(this, strError, "Copy All Favorites", buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
ProgressPanel.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.MdiParent.MainMenuStrip.Enabled = true;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
this.gryFavoritesListTableAdapter.Fill(this.dsFavoritesList.gryFavoritesList);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
lblLoadingData.Visible = false;
}
}
}
validated test to handle the event instead of the TextBox TextChanged event, because every time you insert a character is called the event, while you search with the Validated when actually carried out the validation of txtsearch.
private void txtSearch_Vlidated(object sender, EventArgs e)
{
DataView dv = new DataView(this.dsFavoritesList.gryFavoritesList);
dv.Sort = "Name ASC";
dv.RowFilter = string.Format("Name LIKE '%{0}%'",txtSearch.Text);
dataGridView1.DataSource = dv;
}
Regards.