So basically I am creating a application to where I want to insert an excel sheet inside of the folder path provided.
Here is my Code:
private void BSave_Click(object sender, EventArgs e)
{
FolderBrowserDialog ofd = new FolderBrowserDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
TextOutputFile.Text = ofd.SelectedPath;
}
}
Related
string okunanmetin;
string Progfilepath;
private void btnSelect_Click(object sender, RoutedEventArgs e)
{
richtextboxEdit.Document.Blocks.Remove(richtextboxEdit.Document.Blocks.ElementAt(0));
Progfilepath = "C:/Users/SC/Desktop/test.txt";
okunanmetin = File.ReadAllText(Progfilepath);
richtextboxEdit.Document.Blocks.Add(new Paragraph(new Run(okunanmetin)));
}
As you can see, I can insert a .txt file into the richtextbox. I am making changes in this text that I added. After this change I want to save to the same file.
I tried to do as seen below.
private void btnSave_Click(object sender, RoutedEventArgs e)
{
LoadXamlPackage( "C:/Users/SC/Desktop/test.txt");
}
void LoadXamlPackage(string _fileName)
{
TextRange range;
FileStream fStream;
if (File.Exists(_fileName))
{
range = new TextRange(richtextboxEdit.Document.ContentStart, richtextboxEdit.Document.ContentEnd);
fStream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
range.Save(fStream, DataFormats.Text);
fStream.Close();
}
}
It didn't work the way I wanted.
When I click the save button, it saves the changes but not everything.
Thanks for Support
Hello Guys I solved the problems like the below.
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(Progfilepath))
{
TextRange textRange = new TextRange(richtextboxEdit.Document.ContentStart, richtextboxEdit.Document.ContentEnd);
File.WriteAllText(Progfilepath, textRange.Text);
}
}
Im using this Import Methode, and after editing the File in my application I want to have a button to save the File as a "new File" so the source doesnt get changed only a edited duplication is created.
//import button
private void btn_Import_Click(object sender, RoutedEventArgs e)
{
//delete the filename from the textbox so they dont overlap
tbx_FileName.Clear();
//openFileDialog for file Import
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.InitialDirectory = #"C:\";
var result = dlg.ShowDialog();
tbx_FileName.Text = dlg.FileName;
DataContext = CSVTable.ReadFile(dlg.FileName);
}
//save button
private void btn_Save_Click(object sender, RoutedEventArgs e)
{
//saveFileDialog for file Save
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.InitialDirectory = #"C:\";
dlg.Filter = "CSV file (*.csv)|*.csv|All Files (*.*)|*.*";
var result = dlg.ShowDialog();
if (result.HasValue && result.Value)
{
//Save the file, assuming the DataContext is plain text (i.e. string)
File.WriteAllText(dlg.FileName, DataContext);
}
}
I am just new woking with ProgressBar in WPF. I have a user control like this:
public partial class Import : UserControl
{
public Import()
{
InitializeComponent();
}
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
// Create the OpenFIleDialog object
Microsoft.Win32.OpenFileDialog openPicker = new Microsoft.Win32.OpenFileDialog();
// Add file filters
// We are using excel files in this example
openPicker.DefaultExt = ".xslt";
openPicker.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
// Display the OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openPicker.ShowDialog();
// Check to see if we have a result
if (result == true)
{
// Application now has read/write access to the picked file
filePathTextBox.Text = openPicker.FileName.ToString();
}
}
private void btn_Import_Click(object sender, RoutedEventArgs e)
{
//import all data from excel file to datatable
Workbook wb = new Workbook(filePathTextBox.Text);
// Accessing the worksheet in the Excel file
Worksheet worksheetPro = wb.Worksheets[1];
Worksheet worksheetCat = wb.Worksheets[0];
// Exporting all data by ExportDataTable
DataTable dataTablePro = worksheetPro.Cells
.ExportDataTable(1, 0, worksheetPro.Cells.Rows.Count - 1, worksheetPro.Cells.Columns.Count, false);
DataTable dataTableCat = worksheetCat.Cells
.ExportDataTable(1, 0, worksheetCat.Cells.Rows.Count - 1, worksheetCat.Cells.Columns.Count, false);
//dump data from datatable to SQL server
string connectionString = #"Data Source=DESKTOP-L6OBVA4\SQLEXPRESS;Initial Catalog=QLDB;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
//mapping columns of Datatable with the name of DB
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[0].ColumnName, "Tên");
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[1].ColumnName, "Giá");
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[2].ColumnName, "Số Lượng");
bulkCopy.ColumnMappings.Add(dataTablePro.Columns[3].ColumnName, "Miêu Tả");
//set the destination table name in DB will be affected
bulkCopy.DestinationTableName = "dbo.Products";
try
{
//coppy all rows from nominated datatable and dump it to DB
bulkCopy.WriteToServer(dataTablePro);
dataTablePro.Clear();
using (SqlBulkCopy bulkCopyCat = new SqlBulkCopy(connection))
{
bulkCopyCat.ColumnMappings.Add(dataTableCat.Columns[0].ColumnName, "Loại");
bulkCopyCat.DestinationTableName = "dbo.Categories";
bulkCopyCat.WriteToServer(dataTableCat);
dataTableCat.Clear();
MessageBox.Show("Success!!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
}
The purpose of this user control is: Choose an excel file, then import all data to datatable, finally, dump all data to SQL server. I need to make a processing bar for operation of dumping from datatable to SQL server cause I think it takes long time. So next thing, I create a Process bar window:
public partial class ProgressBar : Window
{
public ProgressBar()
{
InitializeComponent();
}
private void Window_ContentRendered(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
(sender as BackgroundWorker).ReportProgress(i);
//do my operation here
}
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pbStatus.Value = e.ProgressPercentage;
}
}
you can see above snippet code, I have a method named:
worker_DoWork()
it is where I plan to put my operation. And the last thing, I want to take these code lines from user control then put it into worker_DoWork() cause I think these lines take time to handle:
try
{
//coppy all rows from nominated datatable and dump it to DB
bulkCopy.WriteToServer(dataTablePro);
dataTablePro.Clear();
using (SqlBulkCopy bulkCopyCat = new SqlBulkCopy(connection))
{
bulkCopyCat.ColumnMappings.Add(dataTableCat.Columns[0].ColumnName, "Loại");
bulkCopyCat.DestinationTableName = "dbo.Categories";
bulkCopyCat.WriteToServer(dataTableCat);
dataTableCat.Clear();
MessageBox.Show("Success!!!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
what should I do to get it? I heard about delegate and event can give me a choice but i could not find it out by myself. Thanks!
If you do not care about multiple instances of progress dialog. Then try something like this:
Import.xaml:
<Grid>
<Button x:Name="filePicker" Content="ClickMe" Click="filePicker_Click" DockPanel.Dock="Top"/>
<ProgressBar x:Name="progressBar" Minimum="0" Maximum="100" Value="75" DockPanel.Dock="Top" Visibility="Collapsed" />
</Grid>
Import.xaml.cs:
private void filePicker_Click(object sender, RoutedEventArgs e)
{
progressBar.Visibility = Visibility.Visible;
// here you call your batch code
var task = new Task(() => Thread.Sleep(3000));
// after task is done hide progress dialog
task.ContinueWith(x => Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.progressBar.Visibility = Visibility.Collapsed)));
task.Start();
}
(I did not bother with updating the status. It is always 75%.).
So my title is pretty self explanatory, so thus far I have read Microsofts Documentation and watched some Youtube videos regarding my issue here.
Firstly my project code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
foreach (DataRow r in dsEquipment.Tables[0].Rows)
{
DataRow dr = sQTDBDataSet.tblEquipment.NewRow();
dr[0] = r[0];
dr[1] = r[1];
dr[2] = r[2];
dr[3] = r[3];
dr[4] = r[4];
dr[5] = r[5];
dr[6] = r[6];
dr[7] = r[7];
dr[8] = r[8];
dr[9] = r[9];
dr[10] = r[10];
dr[11] = r[11];
dr[12] = r[12];
dr[13] = r[13];
dr[14] = r[14];
dr[15] = r[15];
dr[16] = r[16];
sQTDBDataSet.tblEquipment.Rows.Add(dr);
}
//tblEquipmentTableAdapter.Update(sQTDBDataSet.tblEquipment);
//tableAdapterManager.UpdateAll(sQTDBDataSet);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
this.Validate();
this.tblEquipmentBindingSource.EndEdit();
this.tblEquipmentTableAdapter.Update(this.sQTDBDataSet.tblEquipment);
MessageBox.Show("Update successful");
}
catch (System.Exception ex)
{
MessageBox.Show("Update failed");
}
}
private void btnReadExcel_Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = OFD.FileName;
txtFileName.Text = strfilename;
}
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void tblEquipmentBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.tblEquipmentBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.sQTDBDataSet);
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sQTDBDataSet.tblEquipment' table. You can move, or remove it, as needed.
this.tblEquipmentTableAdapter.Fill(this.sQTDBDataSet.tblEquipment);
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
try
{
// Establish connection between the c# application and the excel file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0");
// Reading the data from the excel file.
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Equipments$]", con);
// All data from the file will be loaded into the dataset.
da.Fill(dsEquipment);
// Show in a message box how many rows of data there is.
//MessageBox.Show(dsEquipment.Tables[0].Rows.Count.ToString());
// Show the data in the data grid view.
dgEquipment.DataSource = dsEquipment.Tables[0];
}
catch
{
MessageBox.Show("Please select the SQT2 Excel sheet.");
}
}
}
}
So my first attempt at tackling the problem was this:
//tblEquipmentTableAdapter.Update(sQTDBDataSet.tblEquipment);
//tableAdapterManager.UpdateAll(sQTDBDataSet);
I get no errors but for some reason my Access Database is not showing the updates.
My second attempt was the following:
private void btnOpenFile_Click(object sender, EventArgs e)
{
try
{
// Establish connection between the c# application and the excel file.
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + txtFileName.Text + ";Extended Properties=Excel 12.0");
// Reading the data from the excel file.
OleDbDataAdapter da = new OleDbDataAdapter("select * from [Equipments$]", con);
// All data from the file will be loaded into the dataset.
da.Fill(dsEquipment);
// Show in a message box how many rows of data there is.
//MessageBox.Show(dsEquipment.Tables[0].Rows.Count.ToString());
// Show the data in the data grid view.
dgEquipment.DataSource = dsEquipment.Tables[0];
}
catch
{
MessageBox.Show("Please select the SQT2 Excel sheet.");
}
}
Which was a seperate button and I obtained this code from Microsofts documentation and changed the variables of the dataset and the database table, no errors... yet STILL my access database is not updating!
Completely stuck right now and any help is appreciated! :)
Thank you!
i want to upload files in a folder and then display that files in datagridview
1) upload files to a folder
2) display that files in datagridview
can any one help me
Try putting this code in your form class and then extend it as you want:
public string Path { get; set; }
private void UploadButton_Click(object sender, EventArgs e)
{
var o = new OpenFileDialog();
o.Multiselect = true;
if(o.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
o.FileNames.ToList().ForEach(file=>{
System.IO.File.Copy(file, System.IO.Path.Combine(this.Path, System.IO.Path.GetFileName(file)));
});
}
this.LoadFiles();
}
private void Form_Load(object sender, EventArgs e)
{
this.LoadFiles();
}
private void LoadFiles()
{
this.Path = #"d:\Test";
var files = System.IO.Directory.GetFiles(this.Path);
this.dataGridView1.DataSource = files.Select(file => new { Name = System.IO.Path.GetFileName(file), Path = file }).ToList();
}
And here is screenshot: