how to add values from var to listview? - c#

public static bool loadFileview(Int64 uname,out string[] filename,out string[] extn)
{
bool b = false;
SCPEntities ent = new SCPEntities();
filename = null;
extn = null;
var data = (from n in ent.User_Data where n.Account_Num == uname select new { n.File_Name, n.Extn }).ToList();
int i = 0;
foreach (var v in data)
{
filename[i] = v.File_Name;
extn[i] = v.Extn;
i++;
}
if(liv1!=n)
{
b = true;
// liv = data;
}
return b;
}
}
method call
protected void Page_Load(object sender, EventArgs e)
{
string[] fname;
string[] extn;
Int64 uname = 12121;
bool b = false;
b= home.loadFileview(uname, out fname,out extn);
if (b)
{
for (int count = 0; count <fname.Length; count++)
{
ListViewItem listItem = new ListViewItem(fname[count]);
listItem.SubItems.Add(extn[count]);
FileListView.Items.Add(listItem);
}
}
I want to bind filename & extn to listview control listview11 dynamically, how?

try this:
protected void Page_Load(object sender, EventArgs e)
{
string[] fname;
string[] extn;
Int64 uname = 12121;
bool b = false;
b= home.loadFileview(uname, out fname,out extn);
if (b)
{
for (int count = 0; count <fname.Length; count++)
{
ListViewItem listItem = new ListViewItem (new[] { fname[count], extn[count]})
FileListView.Items.Add(listItem);
}
}
}

Related

How to use Multi threading in my project?

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.

Find String (or Char[]) in Textfile

I got a Form that wants to have atleast one keyword, like download.
This is the Code to call my OpenFileDialog.
The Class is Form1
public Form1()
{
InitializeComponent();
initListView();
}
private void button1_Click(object sender, EventArgs e)
{
getallfiles.getSelectedFiles(this.listView1);
}
private void initListView()
{
listView1.View = View.Details;
listView1.Columns.Add("Filename", 210, HorizontalAlignment.Left);
listView1.Columns.Add("Size", 60, HorizontalAlignment.Left);
listView1.Columns.Add("Match", 60, HorizontalAlignment.Left);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
listView1.Items.Clear();
seaching.matchResult(progressBar1, listView1, textBox1.Text, textBox2.Text);
}
catch (Exception f)
{
MessageBox.Show(f.ToString());
}
}
Now I get the Multiselected Files and store them in the filePaths String[].
The Class is getallfiles
public static String[] filePaths;
public static void getSelectedFiles(ListView listView)
{
OpenFileDialog openAllFiles = new OpenFileDialog();
openAllFiles.Title = "Select all files you want to look for keywords";
openAllFiles.Multiselect = true;
openAllFiles.Filter = "(*.*)|*.*";
if (openAllFiles.ShowDialog() == DialogResult.OK)
{
filePaths = new string[openAllFiles.FileNames.Length];
int count = 0;
foreach (String file in openAllFiles.FileNames)
{
try
{
ListViewItem masterItem = new ListViewItem(new[] { Path.GetFileName(file), (Math.Round(((new FileInfo(file).Length) / 1024f), 3).ToString()) + " kb"});
listView.Items.Add(masterItem);
filePaths[count] = file;
count++;
}
catch (Exception f)
{
MessageBox.Show(f.ToString());
}
}
}
}
And now my Problemcode. I can filter if there is only the Keyword written, but if it's downloading and I set the Keyword to download my solutions stops working.
The Class is searching
public static void matchResult(ProgressBar progressBar, ListView listView, String key1, String key2)
{
progressBar.Maximum = getallfiles.filePaths.Length;
progressBar.Value = 0;
int count = 0;
bool lockCount = false;
String fileText;
foreach (string file in getallfiles.filePaths)
{
using (StreamReader reader = new StreamReader(getallfiles.filePaths[count]))
{
while ((fileText = reader.ReadLine()) != null)
{
if (String.IsNullOrEmpty(key2) & !String.IsNullOrEmpty(key1))
{
if (fileText.Contains(key1.ToLower()) | fileText.Contains(key1.ToUpper()) | fileText.Contains(key1))
{
ListViewItem masterItem = new ListViewItem(new[] { Path.GetFileName(file), (Math.Round(((new FileInfo(file).Length) / 1024f), 3).ToString()) + " kb" });
listView.Items.Add(masterItem);
count++;
lockCount = true;
reader.Close();
break;
}
}
else if(!String.IsNullOrEmpty(key2))
{
if (fileText.Contains(key1.ToLower()) | fileText.Contains(key2.ToLower()) | fileText.Contains(key1.ToUpper()) | fileText.Contains(key2.ToUpper()) | fileText.Contains(key1) | fileText.Contains(key2))
{
ListViewItem masterItem = new ListViewItem(new[] { Path.GetFileName(file), (Math.Round(((new FileInfo(file).Length) / 1024f), 3).ToString()) + " kb" });
listView.Items.Add(masterItem);
count++;
lockCount = true;
reader.Close();
break;
}
}
}
if (!lockCount)
{
count++;
}
}
}
}
My next Idea was to check for a Char[] but I'm not sure if this is efficient.
I'd let read char for char and store the current line in a char[] and compare if the char[] I'm looking for is in there.

Custom search for AutoCompleteStringCollection

Is there anyway to change the search function for the AutoCompleteStringCollectionclass for the TextBox class? Right now, I have it on the default search function where the beginning letters of my suggestions match the letters of the user input? My suggestions come from a custom source.
You can make your own AutoComplete search - by using TextChange
Here is answer: C# winforms combobox dynamic autocomplete
Code:
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.ToUpper().StartsWith(comboBox1.Text.ToUpper())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}
private void comboBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
int sStart = comboBox1.SelectionStart;
if (sStart > 0)
{
sStart--;
if (sStart == 0)
{
comboBox1.Text = "";
}
else
{
comboBox1.Text = comboBox1.Text.Substring(0, sStart);
}
}
e.Handled = true;
}
}

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;
}

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

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())

Categories

Resources