I am practicing an OCR program using C#, I am not much of a coder so I am trying to find my way around.
1- I OCR some pdf files.
2- I see the output of the OCR.
3- I use UI buttons to browse and then click convert.
4- I have a progress bar on the UI but it does not visually upgrade, while when I log the progressBar.Value I see its numbers are updating.
So I searched around and I found that the issue is I should like stop the thread and create a new one for the Ui to visually update, but I really do not understand that, or even do not know how to do it.
Can someone please help me ? like baby steps.
Also I know I have copied and pasted like alot of code for you to see.
The case is the following:
1- class fmMain: Form has a progressBarIncrementation function, responsible for taking the increment value from a function in processFunctions class.
2- progressBarIncrementation function has progressBar.Value to be updated, I see its value updated.
3- But visually nothing is updated. I tried some threading code, but i do not understand it so.....
class processFunctions
{
Thread newThread = Thread.CurrentThread;
private string invoiceNameIndex = "";
private string invoiceIBANIndex = "";
private string invoiceNumberIndex = "";
private string invoiceDateIndex = "";
private string invoiceSubtotalIndex = "";
private string invoiceVATIndex = "";
private string invoiceTotalIndex = "";
private string[] filePath;
private string[] fileNamePDF;
private int totalNumberOfFiles;
private string InformationNeeded(string wholeRead, string ix)
{
string[] lines = wholeRead.Split(new[] { "\r\n", "\r", "\n", " " }, StringSplitOptions.None);
if(ix.Contains(","))
{
string[] variableIndex = ix.Split(',');
string name = "";
for(int i =0; i < variableIndex.Length; i++)
{
name += lines[Convert.ToInt32(variableIndex[i])];
}
return name;
}
return lines[Convert.ToInt32(ix)];
}
public void ocrFunction(string filePathOnly)
{
var Ocr = new AutoOcr();
var Results = Ocr.ReadPdf(filePathOnly);
var Barcodes = Results.Barcodes;
var Text = Results.Text;
string[] numbers = { invoiceNameIndex, invoiceIBANIndex, invoiceNumberIndex,
invoiceDateIndex, invoiceSubtotalIndex, invoiceVATIndex, invoiceTotalIndex};
string[] results = new string[numbers.Count()];
for (int i = 0; i < numbers.Length; i++)
{
results[i] = InformationNeeded(Text, numbers[i]);
Console.WriteLine(results[i]);
}
Results = null;
Ocr = null;
Barcodes = null;
Text = null;
}
public int browseFile()
{
Thread.CurrentThread.SetApartmentState(ApartmentState.STA);
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}
public void databaseReader()
{
string connectionString;
SqlConnection connection;
connectionString = ConfigurationManager.ConnectionStrings["OCR_App.Properties.Settings.LibraryConnectionString"].ConnectionString;
for (int i = 0; i < fileNamePDF.Length; i++)
{
string fileNameFiltered = fileNamePDF[i].Replace(".pdf", "");
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM invoicesTable WHERE invoiceRef = '" + fileNameFiltered + "'", connection))
{
DataTable invoicesTable = new DataTable();
adapter.Fill(invoicesTable);
DataRow index = invoicesTable.Rows[0];
invoiceNameIndex = (index[1].ToString());
invoiceIBANIndex = (index[2].ToString());
invoiceNumberIndex = (index[3].ToString());
invoiceDateIndex = (index[4].ToString());
invoiceSubtotalIndex = (index[5].ToString());
invoiceVATIndex = (index[6].ToString());
invoiceTotalIndex = (index[7].ToString());
ocrFunction(filePath[i]);
//newThread.Start();
fmMain formFunctions = new fmMain();
//Thread.Yield();
//Thread thread = new Thread(() => formFunctions.ProgressBarIncrementation(progressBarIncrement()));
formFunctions.ProgressBarIncrementation(progressBarIncrement());
}
}
}
public int progressBarIncrement()
{
int incrementValue = 0;
incrementValue = incrementValue + 100 / totalNumberOfFiles;
//Console.WriteLine(incrementValue);
return incrementValue;
}
///////////////////////////////////////////////////////////////////
public partial class fmMain : Form
{
processFunctions processingMain = new processFunctions();
ProgressBar NewprogressBar = new ProgressBar();
private static int incrementbar = 0;
public fmMain()
{
InitializeComponent();
}
[STAThread]
private void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = processingMain.browseFile();
txtBoxFilePath.Text = number.ToString();
}
public void BtnConvert_Click(object sender, EventArgs e)
{
processingMain.databaseReader();
}
private void fmMain_Load(object sender, EventArgs e)
{
}
private void txtBoxFilePath_TextChanged(object sender, EventArgs e)
{
}
private void NumberOfFilesToBeProcessed_Click(object sender,
EventArgs e)
{
}
public void progressBar_Click(object sender, EventArgs e)
{
progressBar.Maximum = 100;
NewprogressBar.Value = progressBar.Value;
}
public void ProgressBarIncrementation(int incrementValue)
{
//Thread.Yield();
//Thread newThread = Thread.CurrentThread;
incrementbar = incrementbar + incrementValue;
progressBar.Visible = true;
progressBar.Value += incrementbar;
Thread thread = new Thread(() => progressBar.Value += incrementbar);
Console.WriteLine(progressBar.Value);
//progressBar.Value += incrementbar;
}
}
If you are needing the progress bar, you might want to consider creating an event to help report progress to your calling application. And you'll want to mark your function browseFile as async and do the following:
public async Task<int> browseFileAsync()
{
await Task.Run(new Action(() => {
OpenFileDialog ofd = new OpenFileDialog();
int numberOfFilesToBeProcessed = 0;
ofd.Filter = "PDF|*.pdf";
ofd.Multiselect = true;
string[] name = new string[2];
if (ofd.ShowDialog() == DialogResult.OK)
{
numberOfFilesToBeProcessed = ofd.FileNames.Length;
filePath = ofd.FileNames;
fileNamePDF = ofd.SafeFileNames;
}
this.totalNumberOfFiles = ofd.FileNames.Length;
return numberOfFilesToBeProcessed;
}));
}
And then in your calling application do:
private async void BtnBrowse_Click(object sender, EventArgs e)
//Browse the file needed to scan.
{
int number = await processMain.browseFileAsync();
txtBoxFilePath.Text = number.ToString();
}
I would also consider not calling a folder browser dialog from your class as this couples your class to a specific implementation. Rather, I would browse for the file from the GUI and pass the selected file(s) to the class.
Related
I always wanted my code to be cleaner and readable. I'm here in order to achieve that. Since i'm a beginner, it's better to learn this early. Like calling all of them in a class, I don't want too see these many codes in my form. I hope someone would be able to give me a suggestions and a proper way of doing these.
Here's my code
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
ADDPReturns returns;
public SIMSSupplier()
{
InitializeComponent();
}
public DataTable dbdataset;
public DataSet ds = new DataSet();
public string ID = "SPPLR-000";
public int DeliveryID, OrderID, ReturnID;
DataView db;
DataTable dt = new DataTable();
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentCell.RowIndex;
SupplierID.Text = Supplierview.Rows[row].Cells[0].Value.ToString();
CompanyName.Text = Supplierview.Rows[row].Cells[1].Value.ToString();
ContactName.Text = Supplierview.Rows[row].Cells[2].Value.ToString();
ContactNumber.Text = Supplierview.Rows[row].Cells[3].Value.ToString();
Date.Text = Supplierview.Rows[row].Cells[4].Value.ToString();
Address.Text = Supplierview.Rows[row].Cells[5].Value.ToString();
Remarks.Text = Supplierview.Rows[row].Cells[6].Value.ToString();
}
private void PurchaseOrder_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseOrder.CurrentCell.RowIndex;
txt_purchase.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
txt_supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
txt_item.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
txt_date.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
txt_quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
txt_cost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
txt_amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
txt_sales.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
txt_code.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
txt_patient.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseDeliveries_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseDeliveries.CurrentCell.RowIndex;
PurchaseID.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
Supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
ItemDescription.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
Dates.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
Quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
Unitcost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
Amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
SalesInvoice.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
Codeitems.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
Patientname.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseReturn_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseReturn.CurrentCell.RowIndex;
txt_return.Text = PurchaseReturn.Rows[row].Cells[0].Value.ToString();
txt_rsupplier.Text = PurchaseReturn.Rows[row].Cells[1].Value.ToString();
txt_ritem.Text = PurchaseReturn.Rows[row].Cells[2].Value.ToString();
txt_rmodel.Text = PurchaseReturn.Rows[row].Cells[3].Value.ToString();
txt_rsrp.Text = PurchaseReturn.Rows[row].Cells[4].Value.ToString();
txt_rcode.Text = PurchaseReturn.Rows[row].Cells[5].Value.ToString();
txt_rdate.Text = PurchaseReturn.Rows[row].Cells[6].Value.ToString();
txt_rremarks.Text = PurchaseReturn.Rows[row].Cells[7].Value.ToString();
}
}
the first can simplify as the following:
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentRow;
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
the second , i would recommend use objects collection as a datasource for your grid. For example :
class DataItem{
public string SupplierID {get;set;}
public string CompanyName {get;set;}
.....
}
Supplierview.DataSource = "collection of DataItem"
then
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var dataItem = dataGridView1.CurrentRow.DataBoundItem as DataItem;
if (dataItem != null)
{
SupplierID.Text = dataItem.SupplierID;
.....
}
}
I suggest using DataBinding for this, then there is no code needed to perform the actions in your sample.
If you dont want to use databinding you could simply make use of private methods to organize your code.
For example
#region Supplier Stuff
private void SupplierViewChanged(DataRow row)
{
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
// put all other helper methods that deal with Supplier here...
#endregion Supplier Stuff
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
SupplierViewChanged(Supplierview.CurrentRow);
}
This makes your code a bit more organized and readable, but databinding is still the method I would choose
at the moment everything I want working is good. But I am trying to clean it up a bit and was looking for some advice when using a generic class. I want to take void update, void add, and void delete and move it to another class then call it in my form when needed. My guess was to try using something like _delete then getters and setters but whenever i tried that i would get errors because I cant recognize listView1. Could someone point me in the right direction? My code is below.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace cartest
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
listView1.View = View.Details;
listView1.FullRowSelect = true;
listView1.Columns.Add("Make", 60);
listView1.Columns.Add("Model", 60);
listView1.Columns.Add("Color", 50);
listView1.Columns.Add("Miles", 50);
listView1.Columns.Add("Condition", 90);
listView1.Columns.Add("Interior", 60);
listView1.Columns.Add("Highway MPG", 90);
listView1.Columns.Add("City MPG", 90);
listView1.Columns.Add("Price", 50);
}
private void add(string make, string model, string color, string miles, string condition, string interior, string highway, string city, string price)
{
string[] row = { make, model, color, miles, condition, interior, highway, city, price }; //adding rows to list
ListViewItem item = new ListViewItem(row);
listView1.Items.Add(item);
}
private void update()
{
listView1.SelectedItems[0].SubItems[0].Text = textBoxMake.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxModel.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxColor.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxMiles.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxCondition.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxInterior.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxHighway.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxCity.Text;
listView1.SelectedItems[0].SubItems[0].Text = textBoxPrice.Text;
//After you update an item it clears the text
textBoxMake.Text = ""; textBoxModel.Text = ""; textBoxColor.Text = ""; textBoxMiles.Text = ""; textBoxCondition.Text = ""; textBoxInterior.Text = ""; textBoxHighway.Text = ""; textBoxCity.Text = ""; textBoxPrice.Text = "";
}
//delete from list
private void delete()
{
if (MessageBox.Show("Are you sure you want to delete this item?", "Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
{
listView1.Items.RemoveAt(listView1.SelectedIndices[0]);
//After you delete it clears text
textBoxMake.Text = ""; textBoxModel.Text = ""; textBoxColor.Text = ""; textBoxMiles.Text = ""; textBoxCondition.Text = ""; textBoxInterior.Text = ""; textBoxHighway.Text = ""; textBoxCity.Text = ""; textBoxPrice.Text = "";
}
}
// add to list
private void buttonAdd_Click(object sender, EventArgs e)
{
add(textBoxMake.Text, textBoxModel.Text, textBoxColor.Text, textBoxMiles.Text, textBoxCondition.Text, textBoxInterior.Text, textBoxHighway.Text, textBoxCity.Text, textBoxPrice.Text);
//After you add an item to list it clears text
textBoxMake.Text = ""; textBoxModel.Text = ""; textBoxColor.Text = ""; textBoxMiles.Text = ""; textBoxCondition.Text = ""; textBoxInterior.Text = ""; textBoxHighway.Text = ""; textBoxCity.Text = ""; textBoxPrice.Text = "";
}
//update item in list
private void buttonUpdate_Click(object sender, EventArgs e)
{
update();
}
//delete a item in list
private void buttonDelete_Click(object sender, EventArgs e)
{
delete();
}
//Click on an item, you get all the values in that row into the textbox
//Used for update purposes
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
textBoxMake.Text = listView1.SelectedItems[0].SubItems[0].Text;
textBoxModel.Text = listView1.SelectedItems[0].SubItems[1].Text;
textBoxColor.Text = listView1.SelectedItems[0].SubItems[2].Text;
textBoxMiles.Text = listView1.SelectedItems[0].SubItems[3].Text;
textBoxCondition.Text = listView1.SelectedItems[0].SubItems[4].Text;
textBoxInterior.Text = listView1.SelectedItems[0].SubItems[5].Text;
textBoxHighway.Text = listView1.SelectedItems[0].SubItems[6].Text;
textBoxCity.Text = listView1.SelectedItems[0].SubItems[7].Text;
textBoxPrice.Text = listView1.SelectedItems[0].SubItems[8].Text;
}
private void buttonSearch_Click(object sender, EventArgs e)
{
}
private void buttonSave_Click(object sender, EventArgs e)
{
string make = textBoxMake.Text;
string model = textBoxModel.Text;
string color = textBoxModel.Text;
string miles = textBoxModel.Text;
string condition = textBoxModel.Text;
string interior = textBoxModel.Text;
string highway = textBoxModel.Text;
string city = textBoxCity.Text;
string price = textBoxPrice.Text;
openFileDialog1.FileName = "cars";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamWriter ap = File.AppendText("cars.txt"))
{
ap.WriteLine(make);
ap.WriteLine(model);
ap.WriteLine(color);
ap.WriteLine(miles);
ap.WriteLine(condition);
ap.WriteLine(interior);
ap.WriteLine(highway);
ap.WriteLine(city);
ap.WriteLine(price);
}
}
}
private void buttonLoad_Click(object sender, EventArgs e)
{
var fileLines = File.ReadAllLines(#"C:\Users\Tyler\Documents\Visual Studio 2015\Projects\Prac\FinalProject\FinalProject\bin\Debug\cars.txt");
for (int i = 0; i + 7 < fileLines.Length; i += 8)
{
listView1.Items.Add(
new ListViewItem(new[]
{
fileLines[i],
fileLines[i + 1],
fileLines[i + 2],
fileLines[i + 3],
fileLines[i + 4],
fileLines[i + 5],
fileLines[i + 6],
fileLines[i + 7],
fileLines[i + 8]
}));
}
}
}
}
Be careful of your usage of the word "generic". Generic class means something very specific in C#. It looks like what you're actually trying to do is just move some functionality out of the form into a separate class. The way to accomplish that might be to pass listView1 into your new class' constructor, which would store it in a class member for add, delete, and move to reference when they're called.
Something like this:
public class MyClass
{
private ListView listView;
public MyClass(ListView lv)
{
listView = lv;
}
public void add(string make, string model, string color, string miles, string condition, string interior, string highway, string city, string price)
{
string[] row = { make, model, color, miles, condition, interior, highway, city, price }; //adding rows to list
ListViewItem item = new ListViewItem(row);
listView.Items.Add(item);
}
// Delete method goes here
// Move method goes here
}
Then to use it, you could do something like:
private void buttonAdd_Click(object sender, EventArgs e)
{
MyClass foo = new MyClass(listView1);
foo.add(textBoxMake.Text, textBoxModel.Text, textBoxColor.Text, textBoxMiles.Text, textBoxCondition.Text, textBoxInterior.Text, textBoxHighway.Text, textBoxCity.Text, textBoxPrice.Text);
... // More code
}
enter image description here
namespace Implementer
{
public partial class MainForm : Form
{
#region intit and globals
public MainForm()
{
InitializeComponent();
DevExpress.XtraGrid.Views.Grid.GridView gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
var transactions = new ObservableCollection<Item>();
for (int i = 0; i <= 100; i++)
{
transactions.Add(new Item { Content = "Item " + i });
}
grdTransactions.AllowDrop = true;
grdTransactions.DataSource = transactions;
dgmWf.AddingNewItem += (s, e) => transactions.Remove(e.Item.Tag as Item);
}
Point mouseDownLocation;
GridHitInfo gridHitInfo;
#endregion
#region events
public void Mainform_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'vA_ERP4_ADMINDataSet.SYSTEM_MODULES' table. You can move, or remove it, as needed.
//Project initiation
//Fill drop down for project list
cmbProject.SelectedIndex = 0;
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtResult = dataAccess.ExecuteQueryDataSet("select MODULE_CODE, MODULE_DESC from SYSTEM_MODULES where module_is_active=1").Tables[0];
cmbProject.DisplayMember = "MODULE_DESC";
cmbProject.ValueMember = "MODULE_CODE";
cmbProject.DataSource = dtResult;
}
private void cmbProject_SelectedIndexChanged(object sender, EventArgs e)
{
lblCurrentProject.Text = cmbProject.Text;
if (cmbProject.Text != null)
{
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtTransactions = dataAccess.ExecuteQueryDataSet("select sys_trans_id, sys_trans_desc1 from WF_SYSTEM_TRANS where MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
grdTransactions.DataSource = dtTransactions;
}
}
private void btnSalesInvoice_Click(object sender, EventArgs e)
{
int sysTransId = 1001;
FillTransactionDetails(sysTransId);
}
#endregion
#region drag drop
private void grdTransactions_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && CanStartDragDrop(e.Location))
{
StartDragDrop();
}
}
private void grdTransactions_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = grdVTransactions.CalcHitInfo(e.Location);
mouseDownLocation = e.Location;
}
private void grdTransactions_MouseLeave(object sender, EventArgs e)
{
if (gridHitInfo != null)
gridHitInfo.View.ResetCursor();
gridHitInfo = null;
}
private bool CanStartDragDrop(Point location)
{
return gridHitInfo.InDataRow && (Math.Abs(location.X - mouseDownLocation.X) > 2 || Math.Abs(location.Y - mouseDownLocation.Y) > 2);
}
public void StartDragDrop()
{
var draggedRow = gridHitInfo.View.GetRow(gridHitInfo.RowHandle) as Item;
var tool = new FactoryItemTool(" ", () => " ", diagram => new DiagramShape(BasicShapes.Rectangle) { Content = draggedRow.Content, Tag = draggedRow }, new System.Windows.Size(150, 100), false);
dgmWf.Commands.Execute(DiagramCommandsBase.StartDragToolCommand, tool, null);
}
#endregion
#region function
private void FillTransactionDetails(int systemTransactionId)
{
//Fill document
//Fill steps
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable transactionDetails = dataAccess.ExecuteQueryDataSet("SELECT DOC_TYPE_DESC1 FROM WF_SYSTEM_TRANS_DT WHERE SYS_TRANS_ID=1001 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionDetails.Rows.Add();
grdDocuments.DataSource = transactionDetails;
grdDocuments.Columns["Details"].DisplayIndex = 2;
grdDocuments.Columns["Delete"].DisplayIndex = 2;
DataTable transactionSteps = dataAccess.ExecuteQueryDataSet("select WF_STEP_DESC1 from WF_STEPS where wf_id= 10101 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionSteps.Rows.Add();
grdSteps.DataSource = transactionSteps;
}
#endregion
}
public class Item
{
public string Content { get; set; }
}
}
I don't really know where is the mistake and have been looking at it for the past few days and searching for an answer but no luck so I'd be so happy if you could help me out. It was working without the data fetching. but after calling the data it doesn't work. drag it from the grid view and when it reaches the diagram control it would turn into a rectangle with a tag property of it's ID.. With regards to the connection string.. I created a global function to just call it on the main form.
I want to invoke timer in my c# code on button click.It works well in form load event but didn't work in button click.Please help me to fix it.Thank's in advance.
My code is Here:
public partial class Form1 : Form
{
public int TimeTaken;
public Form1()
{
InitializeComponent();
lblFilesCount.Text = lblFoldersCount.Text = "0";
}
private void btnFolderBrowse_Click(object sender, EventArgs e)
{
DialogResult result = fbdFoldersFiles.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = Directory.GetFiles(fbdFoldersFiles.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
txtFolderPath.Text = fbdFoldersFiles.SelectedPath;
}
private void btnDeleteFiles_Click(object sender, EventArgs e)
{
timerDelete.Enabled= true;
string path = fbdFoldersFiles.SelectedPath;
DirectoryInfo dirFirst = new DirectoryInfo(path);
foreach (FileInfo file in dirFirst.GetFiles())
{
timerDelete.Enabled = true;
DateTime dt = File.GetLastWriteTime(file.FullName);
if (dt < dtpDate.Value)
{
DeleteFiles(file);
}
}
string[] dirArray = Directory.GetDirectories(path, "*", SearchOption.AllDirectories).ToArray();
Array.Reverse(dirArray);
foreach (var directory in dirArray)
{
if (Directory.GetFiles(directory).Length > 0 || Directory.GetDirectories(directory).Length>0)
{
DirectoryInfo dir = new DirectoryInfo(directory);
FileInfo[] files = dir.GetFiles().ToArray();
foreach (FileInfo file in files)
{
timerDelete.Enabled = true;
DateTime dt = File.GetLastWriteTime(file.FullName);
if (dt < dtpDate.Value)
{
DeleteFiles(file);
}
}
if (Directory.GetFiles(directory).Length == 0 )
{
dir.Delete(true);
lblFoldersCount.Text = (Convert.ToInt32(lblFoldersCount.Text) + 1).ToString();
}
}
}
timerDelete.Enabled = false;
}
protected void DeleteFiles(FileInfo DeleteFile)
{
dgvDisplayFilesInfo.Rows.Add();
int RowIndex = dgvDisplayFilesInfo.RowCount - 1;
DataGridViewRow r = dgvDisplayFilesInfo.Rows[RowIndex];
r.Cells["dgvColoumnSrNo"].Value = RowIndex+1;
r.Cells["dgvColumnFullName"].Value = DeleteFile.Name;
r.Cells["dgvColumnPath"].Value = DeleteFile.Directory;
DeleteFile.Delete();
lblFilesCount.Text = (Convert.ToInt32(lblFilesCount.Text)+1).ToString();
}
private void timerDelete_Tick(object sender, EventArgs e)
{
TimeTaken = TimeTaken++;
lblShowTimeTaken.Text = TimeTaken.ToString();
}
}
First of all you are setting the Enabled=True in the foreach which I don't think it's what you intended. 2nd of all, why don't you use Stopwatch component. It's much easier to use.
Stopwatch sw = new Stopwatch();
sw.Start();
....
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds.ToString())
I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}