How to load data from a specific column in datatable - winforms

I have a datatable that I created programmatically (no connection used etc) and in my datatable I have 2 columns. I would only like to export the value from 2nd column to excel. For my code below, it export the data from both columns inside excel. How do I write for exporting only a specific column?
private void button2_Click(object sender, EventArgs e)
{
using (ExcelPackage pck = new ExcelPackage())
{
string filepath = "C:\\Trial.xlsx";
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("test");
ws.Cells["A1"].LoadFromDataTable(dt1, false);
pck.SaveAs(new FileInfo(filepath));
}
this.Close();
}

Copy your DataTable into temporary table and remove columns, you don't want and then export to excel.
Example:
DataTable tempDataTable;
tempDataTable = table.Copy();
tempDataTable.Columns.Remove("NameOfColumnYouDontWant");
In your code:
private void button2_Click(object sender, EventArgs e)
{
using (ExcelPackage pck = new ExcelPackage())
{
string filepath = "C:\\Trial.xlsx";
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("test");
DataTable tempDataTable;
tempDataTable = dt1.Copy();
tempDataTable.Columns.Remove("NameOfColumnYouDontWant");
# Remove all columns you don't need
ws.Cells["A1"].LoadFromDataTable(tempDataTable, false);
pck.SaveAs(new FileInfo(filepath));
}
this.Close();
}

Related

Inserting Excel File in provided folder

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

Pass operation from user control to Worker_DoWork in other window

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%.).

Get the new added row values for insert in grid control devexpress winform

i'am actually trying to get the new values of the new added row from my grid control (devexpress) thant i set "AllowAddRows" to true;
i can get the updated one like this
Object row = ListeQual.GetRow(ListeQual.FocusedRowHandle);
but i can get the new values in add event for insert
Try this :
private void ListeQual_ValidateRow(object sender, ValidateRowEventArgs e)
{
GridView view = sender as GridView;
if (view.IsNewItemRow(e.RowHandle))
{
DataRow row = view.GetDataRow(e.RowHandle);
}
}
You can create a button how allow to add new row :
private void AddNewRow_Click(object sender, EventArgs e)
{
// (ListeQual.MainView as DevExpress.XtraGrid.Views.Grid.GridView).AddNewRow();
ListeQual.AddNewRow();
}
And a create a methode how you can pass the new row as parameter for saving in datatbase :
private int insertData(DataRow dr)
{
string connectionString = "your connection string here";
int nb = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Col1, Col2, Col3) VALUES (#col1, #col2, #col3)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#col1", dr[0]);
cmd.Parameters.AddWithValue("#col2", dr[1]);
cmd.Parameters.AddWithValue("#col3", dr[2]);
connection.Open();
nb= cmd.ExecuteNonQuery();
}
return nb;
}
Finally you can handle the event ValidateRow :
private void ListeQual_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
{
GridView view = ListeQual as GridView;
if (view.IsNewItemRow(e.RowHandle))
{
DataRow dw = view.GetDataRow(e.RowHandle);
insertData(dw);
}
}

How do I export data from a datagridview/data set into an Access Database? [C#]

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!

Deleting from a Data Grid View

I have created a windows form application. I want this application to be able to use Linq to SQL to search for a record, and then for that record to be selected from a data grid view and deleted.
The form contains a textbox to enter the parameter, a search button and a delete button and a datagrid.
I have the search part working correctly and the data grid is populated but don't know how to implement clicking on the record in the data grid and deleting it.
Update - I have solved the solution. Changes have only been made to the btn_Delete_Click event handler so I have included the updated code for his button after the main code.
namespace DeleteForm
{
public partial class Form1 : Form
{
LinqtoStudentDataContext linqStud = new LinqtoStudentDataContext();
public Form1()
{
InitializeComponent();
}
private void btnDelete_Click(object sender, EventArgs e)
{
}
private void btnSearch_Click(object sender, EventArgs e)
{
var lastName = from stud in linqStud.Students
where txtFind.Text == stud.LastName
select stud;
dataGridView1.DataSource = lastName;
}
}
}
Updated code -
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.dataGridView1.SelectedRows.Count > 0)
{
dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[0].Index);
//linqStud.Students.DeleteAllOnSubmit();
linqStud.SubmitChanges();
}
}
First, set selection mode of DataGridView to FullRowSelect. Next, when assigning DataSource you should call ToList() - you can't use query as data source:
private void btnSearch_Click(object sender, EventArgs e)
{
var lastName = txtFind.Text;
var students = from stud in linqStud.Students
where stud.LastName == lastName
select stud;
dataGridView1.DataSource = students.ToList();
}
Get selected rows, and remove databound items (students) from context:
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
var student = row.DataBoundItem as Student;
linqStud.Students.Remove(student);
linqStud.SaveChanges();
}
}

Resources