Reading From a Text File in C# - c#

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

Related

C# how to get info from one form that is saved to a txt file to show on another form

Okay, sorry this is my first time posting but, here we go. I am writing a program that has one form that shows info that is stored in a .txt file. There is a new button that allows me to put the new info to that file using another form. When I save the info, it stores it in the file, but When it goes back to the original form, the info doesn't display. Below is all the code I have put in. Yes, I am new to C#.
First Form
public partial class Form1 : Form
{
public List<String> pateintNumber;
public List<String> patientFirstName;
public List<String> patientMiddleName;
public List<String> patientLastName;
public List<String> patientDOB;
public bool test = false;
public int counter;
public int g;
public void cacheInfo()
{
StreamReader getLength = new StreamReader("../../../patient info.txt");
string lineInfo = getLength.ReadLine();
counter = 0;
while (lineInfo != null)
{
counter++;
lineInfo = getLength.ReadLine();
}
getLength.Close();
//MessageBox.Show(Convert.ToString(counter));
pateintNumber = new List<String>(1);
patientFirstName = new List<String>(1);
patientMiddleName = new List<String>(1);
patientLastName = new List<String>(1);
patientDOB = new List<String>(1);
g = 0;
StreamReader getInfo = new StreamReader("../../../patient info.txt");
lineInfo = getInfo.ReadLine();
while (g < counter)
{
//MessageBox.Show(lineInfo);
String[] info = lineInfo.Split(',');
pateintNumber.Add(info[0]);
patientFirstName.Add(info[1]);
patientMiddleName.Add(info[2]);
patientLastName.Add(info[3]);
patientDOB.Add(info[4]);
lineInfo = getInfo.ReadLine();
g++;
}
g = 0;
lbPateintNumber.Text = pateintNumber[g];
lbPateintFIrstName.Text = patientFirstName[g];
lbPateintMiddleName.Text = patientMiddleName[g];
lbPateintLastName.Text = patientLastName[g];
lbPateintDOB.Text = patientDOB[g];
getInfo.Close();
}
public Form1()
{
InitializeComponent();
cacheInfo();
}
private void Form_Shown(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
g++;
if (g > counter - 1)
{
g = 0;
lbPateintNumber.Text = pateintNumber[g];
lbPateintFIrstName.Text = patientFirstName[g];
lbPateintMiddleName.Text = patientMiddleName[g];
lbPateintLastName.Text = patientLastName[g];
lbPateintDOB.Text = patientDOB[g];
}
else
{
lbPateintNumber.Text = pateintNumber[g];
lbPateintFIrstName.Text = patientFirstName[g];
lbPateintMiddleName.Text = patientMiddleName[g];
lbPateintLastName.Text = patientLastName[g];
lbPateintDOB.Text = patientDOB[g];
}
}
private void button1_Click(object sender, EventArgs e)
{
g--;
if (g < 0)
{
g = counter - 1;
lbPateintNumber.Text = pateintNumber[g];
lbPateintFIrstName.Text = patientFirstName[g];
lbPateintMiddleName.Text = patientMiddleName[g];
lbPateintLastName.Text = patientLastName[g];
lbPateintDOB.Text = patientDOB[g];
}
else
{
lbPateintNumber.Text = pateintNumber[g];
lbPateintFIrstName.Text = patientFirstName[g];
lbPateintMiddleName.Text = patientMiddleName[g];
lbPateintLastName.Text = patientLastName[g];
lbPateintDOB.Text = patientDOB[g];
}
}
private void barNew_Click(object sender, EventArgs e)
{
Form2 frm = new Form2();
frm.ShowDialog();
}
}//end of program
Second Form
public partial class Form2 : Form
{
public string newFirstName;
public string newMiddleName;
public string newLastName;
public string newDOB;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
StreamReader getLength = new StreamReader("../../../patient info.txt");
string lineInfo = getLength.ReadLine();
while (lineInfo != null)
{
counter++;
lineInfo = getLength.ReadLine();
}
getLength.Close();
counter++;
StreamWriter writeNewPatient = new StreamWriter("../../../patient info.txt", true );
writeNewPatient.WriteLine("000" + counter + ", " + tbFirstName.Text + ", " + tbMiddleName.Text + ", " + tbLastName.Text + ", " + tbDOB.Text);
writeNewPatient.Flush();
writeNewPatient.Close();
Form1 frm = new Form1();
frm.pateintNumber.Add("000" + counter);
frm.patientFirstName.Add(tbFirstName.Text);
frm.patientMiddleName.Add(tbMiddleName.Text);
frm.patientLastName.Add(tbLastName.Text);
frm.patientDOB.Add(tbDOB.Text);
frm.counter = frm.counter++;
this.Close(); //to turn off current app
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
} //end of program
Make your second form like
public partial class Form2 : Form
{
public string newFirstName;
public string newMiddleName;
public string newLastName;
public string newDOB;
public Form2()
{
InitializeComponent();
}
private Form1 m_MainForm;
public Form2(Form1 form)
{
InitializeComponent();
m_MainForm = form;
}
private void button1_Click(object sender, EventArgs e)
{
int counter = 0;
StreamReader getLength = new StreamReader("../../../patient info.txt");
string lineInfo = getLength.ReadLine();
while (lineInfo != null)
{
counter++;
lineInfo = getLength.ReadLine();
}
getLength.Close();
counter++;
StreamWriter writeNewPatient = new StreamWriter("../../../patient info.txt", true );
writeNewPatient.WriteLine("000" + counter + ", " + tbFirstName.Text + ", " + tbMiddleName.Text + ", " + tbLastName.Text + ", " + tbDOB.Text);
writeNewPatient.Flush();
writeNewPatient.Close();
Form1 frm = new Form1();
frm.pateintNumber.Add("000" + counter);
frm.patientFirstName.Add(tbFirstName.Text);
frm.patientMiddleName.Add(tbMiddleName.Text);
frm.patientLastName.Add(tbLastName.Text);
frm.patientDOB.Add(tbDOB.Text);
frm.counter = frm.counter++;
if (!Object.ReferenceEquals(null, m_MainForm))
{
m_MainForm.cacheInfo();
}
this.Close(); //to turn off current app
}
private void button2_Click(object sender, EventArgs e)
{
if (!Object.ReferenceEquals(null, m_MainForm))
{
m_MainForm.cacheInfo();
}
this.Close();
}
} //end of program
and call second form from first one like this
private void barNew_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.ShowDialog();
}

Stop SelectedValueChanged event

I just want to ask how to stop the selected value changed event in my code. I have both SelectedValueChanged event and SelectedIndexChanged event. I am using SelectedIndexChanged event because to find any duplication on my gridview for you to understand, here is my code.
SelectedValueChanged code:
private void cmbField_SelectedValueChanged(object sender, EventArgs e)
{
DataGridViewRow GridRowLoc = this.dgvFilter.CurrentRow;
AddGrid(iRowIdx);
int iRowCount = this.dgvFilter.RowCount - 1;
if (this.cmbField.Text != "System.Data.DataRowView")
{
this.dgvFilter.Rows[iRowIdx].Cells["ColumnFieldName"].Value = this.cmbField.Text;
this.dgvFilter.Rows[iRowIdx].Cells["FieldName"].Value = this.cmbField.SelectedValue;
if (iRowCount <= iRowIdx)
{
DataRow drow = dttable.NewRow();
drow["ColumnNames"] = this.cmbField.Text;
drow["FieldName"] = this.cmbField.SelectedValue;
drow["Alias"] = string.Empty;
drow["DataType"] = string.Empty;
drow["Outputs"] = false;
drow["SortType"] = string.Empty;
drow["SortOrder"] = string.Empty;
drow["GroupBy"] = string.Empty;
drow["Filter"] = string.Empty;
drow["Or1"] = string.Empty;
drow["Or2"] = string.Empty;
drow["Or3"] = string.Empty;
drow["Or4"] = string.Empty;
drow["Or5"] = string.Empty;
drow["Or6"] = string.Empty;
drow["Or7"] = string.Empty;
drow["Or8"] = string.Empty;
drow["Or9"] = string.Empty;
drow["Or10"] = string.Empty;
dttable.Rows.Add(drow);
}
else
{
int irow = 0;
foreach (DataRow dr in dttable.Rows)
{
if (irow == iRowIdx)
{
dr["ColumnNames"] = this.cmbField.Text;
dr["FieldName"] = this.cmbField.SelectedValue;
}
irow++;
}
}
CheckAlias(iRowIdx, this.cmbField.Text, dgvFilter);
checkcellvalue(this.cmbField.Text, iRowIdx);
CheckSorting();
if (bGroupBySelected == true)
{
this.dgvFilter.Rows[iRowIdx].Cells["GroupBy"].Value = "Group By";
}
this.dgvFilter.DataSource = dttable;
dsFilter.AcceptChanges();
this.cmbField.Visible = false;
}
//checkcellvalue(this.cmbField.Text, iRowIdx);
//MessageBox.Show(arr_Filter[0]);
CheckoutputEnable();
}
Then here is my SelectedIndexChanged code:
private void cmbField_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (dgvFilter.Rows.Count > 1)
{
int count = this.dgvFilter.Rows.Count;
DataRowView oDataRowView = cmbField.SelectedItem as DataRowView;
string sValue = string.Empty;
if (oDataRowView != null)
{
sValue = oDataRowView.Row["FieldDescription"] as string;
}
for (int j = 0; j < count; j++)
{
sValue = this.cmbField.Text;
if ((j + 2) != dgvFilter.Rows.Count)
{
if ((sValue == this.dgvFilter.Rows[j].Cells["ColumnFieldName"].Value.ToString()))
{
if (this.dgvFilter.Rows.Count > 2)
{
MessageBox.Show("Field already in the list");
DataGridViewRow GridRowLoc2 = this.dgvFilter.CurrentRow;
this.dgvFilter.Rows.Remove(GridRowLoc2);
break;
}
}
}
}
}
}
catch (Exception ex)
{
}
}
My code upon loading the form is this in case you guys need.
private void FormAdhocReportViewer_Load(object sender, EventArgs e)
{
try
{
//string sample = "";
sXMLResult = SQLScript;
AddGrid(0);
adhoc.RowID = CurrentUserNameRowID;
adhoc.FieldGroup = toolStripReportGroup.Text;
XMLDOC = adhoc.get_sp_Get_Field_Settings();
if (RowID == "0")
{
// XMLDOC = adhoc.get_sp_Get_Field_Settings();
LoadDataSet(XMLFILTER);
}
else
{
// XMLDOC = sXMLFieldSettings;
XMLFieldQuery = XMLFieldQuery.Replace("#", "<").Replace("+", ">").Replace("*", "/");
LoadDataSet(XMLFieldQuery);
}
LoadComboField();
}
catch { }
}
LoadComboField is for the items in the combobox, the code is this
private void LoadComboField()
{
ReadXMLData(XMLDOC, dsCombo);
dt = dsCombo.Tables[0];
DataView dv1 = new DataView(dsCombo.Tables[0]);
this.cmbField.Items.Clear();
this.cmbField.DataSource = dv1;
this.cmbField.DisplayMember = "FieldDescription";
this.cmbField.ValueMember = "FieldName";
}
Everytime the code
DataGridViewRow GridRowLoc2 = this.dgvFilter.CurrentRow;
this.dgvFilter.Rows.Remove(GridRowLoc2);
executes the event SelectedValueChanged executes to.. I just want to stop the SelectedValueChangedEvent it's so hard to explain because my code is too complicated.
What about simply removing the event handler?
Just do:
if (<whatever>)
{
this.cmbField.SelectedValueChanged -= cmbField_SelectedValueChanged;
}

Read and change values of a gridview in c#

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)
{
}
}

Assigning checkbox a value from gridview

I am selecting a row from Gridview, working good except for checkbox, like I am assigning value of checkbox retreived from gridview to checkbox that is placed on web form but it isn't represented by checkbox on form, it shows empty checkbox in every case
if (gridviewDesignations.SelectedRow.Cells[5].Text == " ")
{
chkIsHead.Text = gridviewDesignations.SelectedRow.Cells[5].Text;
}
in short, checkbox is not picking value from gridview
Update:
tried this too:
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
Update:
my full code:
public partial class frmDesignations : System.Web.UI.Page
{
AccessibleVariables accessVariables = new AccessibleVariables(); //Used to access global variables
public void Clear(params TextBox[] txtBoxes)
{
foreach (TextBox txtbx in txtBoxes)
{
txtbx.Text = "";
}
}
public void fillddlDepartments()
{
ManageDepartmentsBizz mngDepBizz = new ManageDepartmentsBizz();
DataSet ds = (DataSet)mngDepBizz.SelectDepartments();
if (ds.Tables[0].Rows.Count != 0)
{
ddlDepartments.DataValueField = "DepID";
ddlDepartments.DataTextField = "DepName";
ddlDepartments.DataSource = ds.Tables[0];
// ddlDepartments.SelectedIndex = -1;
ddlDepartments.DataBind();
ddlDepartments.Items.Insert(0, "--Select--");
}
//else
// ddlDepartments.SelectedIndex = -1;
}
protected void Page_Load(object sender, EventArgs e)
{
if (Session.Count <= 0)
{
Response.Redirect("login.aspx");
}
lblMsgPopUp.Visible = false;
if (!IsPostBack)
{
fillddlDepartments();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(-1, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead);
//-1 is bogus,used to fill parameters criteria i.e no of params
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Insert(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Saved";
HiddenFieldShowMessage.Value = "True";
Clear(txtTitle, txtSelectedID, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "RecordAlreadyExists";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotSaved";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnSearchPopup_Click(object sender, EventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepsBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepsBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
lblMsgPopUp.Visible = false;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
else
{
lblMsgPopUp.Visible = true;
gridviewDesignations.Visible = false;
}
}
protected void gridviewDesignations_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
string DesignationTitle = txtDesignationPopUp.Text;
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
DataSet ds = (DataSet)mngDepBizz.Select(DesignationTitle);
if (ds.Tables[0].Rows.Count != 0)
{
gridviewDesignations.PageIndex = e.NewPageIndex;
gridviewDesignations.DataSource = ds.Tables[0];
gridviewDesignations.DataBind();
gridviewDesignations.Visible = true;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (gridviewDesignations.SelectedRow != null)
{
if (gridviewDesignations.SelectedRow.Cells[1].Text == " ")
{
txtSelectedID.Text = string.Empty;
}
else
{
txtSelectedID.Text = gridviewDesignations.SelectedRow.Cells[1].Text;
}
if (gridviewDesignations.SelectedRow.Cells[2].Text == " ")
{
txtTitle.Text = string.Empty;
}
else
{
txtTitle.Text = gridviewDesignations.SelectedRow.Cells[2].Text;
}
if (gridviewDesignations.SelectedRow.Cells[3].Text == " ")
{
ddlDepartments.SelectedValue = string.Empty;
}
else
{
ddlDepartments.SelectedValue = gridviewDesignations.SelectedRow.Cells[3].Text;
accessVariables.DepID = Convert.ToInt32(gridviewDesignations.SelectedRow.Cells[3].Text);
ViewState["depID"] = accessVariables.DepID;
}
if (gridviewDesignations.SelectedRow.Cells[4].Text == " ")
{
txtContactNo.Text = string.Empty;
}
else
{
txtContactNo.Text = gridviewDesignations.SelectedRow.Cells[4].Text;
}
CheckBox chkIsHead = (CheckBox) gridviewDesignations.SelectedRow.Cells[5].Controls[0];
if (chkIsHead.Checked == false)
{
chkIsHead.Checked = false;
}
else
{
chkIsHead.Checked = true;
}
gridviewDesignations.DataBind();
gridviewDesignations.SelectedIndex = -1;
HiddenFieldShowHideButtons.Value = "True";
}
}
protected void btnUpdatePopUp_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(txtSelectedID.Text);
int DepartmentID = Convert.ToInt32(ddlDepartments.SelectedValue);
bool IsHead = Convert.ToBoolean(chkIsHead.Checked);
DesignationsBizz DesigBizz = new DesignationsBizz(id, txtTitle.Text, DepartmentID, txtContactNo.Text, IsHead );
ManageDesignationsBizz mngDesigBizz = new ManageDesignationsBizz();
bool Result = mngDesigBizz.Update(DesigBizz);
if (Result == true)
{
HiddenFieldSetMessage.Value = "Updated";
HiddenFieldShowMessage.Value = "True";
Clear(txtSelectedID, txtTitle, txtContactNo);
}
else
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotUpdated";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnDeletePopUp_Click(object sender, EventArgs e)
{
try
{
int ID = Convert.ToInt32(txtSelectedID.Text.Trim());
ManageDesignationsBizz mngDepBizz = new ManageDesignationsBizz();
mngDepBizz.Delete(ID);
Clear(txtTitle, txtSelectedID, txtContactNo);
HiddenFieldSetMessage.Value = "Deleted";
HiddenFieldShowMessage.Value = "True";
}
catch (Exception)
{
HiddenFieldSetMessage.Value = "NotDeleted";
HiddenFieldShowMessage.Value = "True";
}
}
protected void btnClosePopup_Click(object sender, EventArgs e)
{
Clear(txtTitle, txtSelectedID, txtContactNo);
}
protected void ddlDepartments_SelectedIndexChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
else
{
accessVariables.DepID = Convert.ToInt32(ddlDepartments.SelectedValue);
ViewState["depID"] = accessVariables.DepID;
}
}
protected void chkIsHead_CheckedChanged(object sender, EventArgs e)
{
if (txtSelectedID.Text != "")
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
else
{
int DepID = Convert.ToInt32(ViewState["depID"]);
ManageDesignationsBizz mngDesig = new ManageDesignationsBizz();
bool isHead = mngDesig.SelectIsHeadExistsByDepID(DepID);
if (isHead == true)
{
HiddenFieldSetMessage.Value = "HeadExists";
HiddenFieldShowMessage.Value = "True";
chkIsHead.Checked = false;
}
}
}
}
I believe the following is what you need to do:
Then select EditProgrammatically.
I'm not sure if yoou'll need to manually put data into the grid though but that won't be too hard. Examples can be seen here : http://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
PS : You can set the DataSource in the grid view to the DataTable.

C# DataGridView Filter works but after using the Filter the selected row doesn't return the right data

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.

Categories

Resources