DevExpress export GridView to Excel - c#

I really need help with this.. I can't find any example on the internet
I am using DevExpress GridView I need to send it to excel and I'm getting problems to loop to every cell and column because DevExpress contains different methods then the DataGridView
that's the code that i'm trying to write.. I really Appreciate your help
public class Form1 : System.Windows.Forms.Form
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
string FirstName = "First Name";
string FatherName = "Father Name";
string LastName = "Last Name";
}
public Form1()
{
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 20;
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
private void simpleButton1_Click(object sender, System.EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=C:\\Users\\pc\\Documents\\Emp.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes\"";
con.Open();
DataTable dtSchema;
dtSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
OleDbCommand Command = new OleDbCommand ("select * FROM [" + dtSchema.Rows[0]["TABLE_NAME"].ToString() + "]", con);
OleDbDataAdapter da = new OleDbDataAdapter(Command);
DataSet ds = new DataSet ();
da.Fill(ds);
dataGrid1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
private void ExportBtn_Click(object sender, System.EventArgs e)
{
for (int i = 1; i < gridView3.Columns.Count + 1; i++)
{
//ExcelApp.Cells[1, i] = gridView3.Columns[i].HeaderStyleName;
}
for (int i = 0; i< gridView3.RowCount - 1; i++)
{
for (int j = 0; j < gridView3.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = gridView3.Columns[j].ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\Users\\pc\\Emp.xlsx");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
My problem is in the Export button the click event.. There's no such thing as Row()

To know various export methods of XtraGrid, go through Export Methods and Settings
Use GridControl.ExportToXls(String) Method
Example code snippet:
private void mnuExportTable_ItemClick_1(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
using (SaveFileDialog saveDialog = new SaveFileDialog())
{
saveDialog.Filter = "Excel (2003)(.xls)|*.xls|Excel (2010) (.xlsx)|*.xlsx |RichText File (.rtf)|*.rtf |Pdf File (.pdf)|*.pdf |Html File (.html)|*.html";
if (saveDialog.ShowDialog() != DialogResult.Cancel)
{
string exportFilePath = saveDialog.FileName;
string fileExtenstion = new FileInfo(exportFilePath).Extension;
switch (fileExtenstion)
{
case ".xls":
gridControl.ExportToXls(exportFilePath);
break;
case ".xlsx":
gridControl.ExportToXlsx(exportFilePath);
break;
case ".rtf":
gridControl.ExportToRtf(exportFilePath);
break;
case ".pdf":
gridControl.ExportToPdf(exportFilePath);
break;
case ".html":
gridControl.ExportToHtml(exportFilePath);
break;
case ".mht":
gridControl.ExportToMht(exportFilePath);
break;
default:
break;
}
if (File.Exists(exportFilePath))
{
try
{
//Try to open the file and let windows decide how to open it.
System.Diagnostics.Process.Start(exportFilePath);
}
catch
{
String msg = "The file could not be opened." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
MessageBox.Show(msg, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
String msg = "The file could not be saved." + Environment.NewLine + Environment.NewLine + "Path: " + exportFilePath;
MessageBox.Show(msg, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Reference:
Exporting Several XtraGrid Controls to a Single Excel File

try below code. SaveFileDialog1 is tool
also add required references --
Try
Dim sv As New SaveFileDialog1
SaveFileDialog1.Filter = "Excel Workbook|*.xlsx"
If SaveFileDialog1.ShowDialog() = DialogResult.OK And SaveFileDialog1.FileName <> Nothing Then
If SaveFileDialog1.FileName.EndsWith(".xlsx") Then
Dim path = SaveFileDialog1.FileName.ToString()
GridControlAFP.ExportToXlsx(path)
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
xlWorkBook = xlApp.Workbooks.Open(path)
xlWorkSheet = xlWorkBook.Sheets("Sheet")
xlWorkSheet.Range("A1:XFD1").EntireColumn.AutoFit()
xlWorkBook.Save()
xlWorkBook.Close()
xlApp.Quit()
End If
MessageBox.Show("Data Exported to :" + vbCrLf + SaveFileDialog1.FileName, "Business Intelligence Portal", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1)
SaveFileDialog1.FileName = Nothing
End If
Catch ex As Exception
End Try

The selectgridvalues function returns the values in the Database in Datatable format.
Calling this function in the show button sets these values in the gridcontrol.
Export button exports the values into an Excel sheet in .xlsx format
//function to get values from DataTable to gridControl Devexpress
public DataTable selectgridvalues()
{
SqlConnection con;
con = new SqlConnection();
con.ConnectionString = "server='SERVER';uid='sa';pwd='1234';database='DBName'";
con.Open();
SqlDataAdapter adp = new SqlDataAdapter("select * from Tablename order by id ", con);
DataTable dt = new DataTable();
adp.Fill(dt);
gridControl1.DataSource =dt;
}
//code on showdatagridview values button
public void buttonShow_Click(object sender, EventArgs e)
{
gridControl1.DataSource = selectgridvalues();
}
//code on export to excel button
private void buttonExportExcel_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialogExcel = new SaveFileDialog();
saveFileDialogExcel.Filter = "Excel files (*.xlsx)|*.xlsx";
if (saveFileDialogExcel.ShowDialog() == DialogResult.OK)
{
string exportFilePath = saveFileDialogExcel.FileName;
gridControl1.DataSource = selectgridvalues();
gridControl1.ExportToXlsx(exportFilePath);
}
}

Related

Trimming all cells in DataTable

I am using the below code to trim all cells in my DataTable.
The problem is, that I am doing it through a loop, and depending on what I fill the DataTable with, if it has 1500 rows and 20 columns, the loop takes a really, really long time.
DataColumn[] stringColumns = dtDataTable.Columns.Cast<DataColumn>().Where(c => c.DataType == typeof(string)).ToArray();
foreach (DataRow row in dtDataTable.Rows)
{
foreach (DataColumn col in stringColumns)
{
if (row[col] != DBNull.Value)
{
row.SetField<string>(col, row.Field<string>(col).Trim());
}
}
}
And here is how I am importing my Excel sheet to the DataTable:
using (OpenFileDialog ofd = new OpenFileDialog() { Title = "Select File", Filter = "Excel WorkBook|*.xlsx|Excel WorkBook 97-2003|*.xls|All Files(*.*)|*.*", Multiselect = false, ValidateNames = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
String PathName = ofd.FileName;
FileName = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName);
strConn = string.Empty;
FileInfo file = new FileInfo(PathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + PathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + PathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
}
}
else
{
return;
}
}
using (OleDbConnection cnnxls = new OleDbConnection(strConn))
{
using (OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", "Sheet1"), cnnxls))
{
oda.Fill(dtDataTableInitial);
}
}
//Clone dtDataTableInitial so that I can have the new DataTable in String Type
dtDataTable = dtDataImportInitial.Clone();
foreach (DataColumn col in dtDataTable.Columns)
{
col.DataType = typeof(string);
}
foreach (DataRow row in dtDataImportInitial.Rows)
{
dtDataTable.ImportRow(row);
}
Is there a more efficient way of accomplishing this?
EDIT: As per JQSOFT's suggestion, I am using OleDbDataReader now, but am still running two issues:
One: SELECT RTRIM(LTRIM(*)) FROM [Sheet1$] doesn't seem to work.
I know that it is possible to select each column one by one, but the number of and header of the columns in the excel sheet is random, and I am not sure how to adjust my SELECT string to account for this.
Two: A column whose rows are mostly populated with numbers, but have a few rows with letters seem to have those rows with letters omitted. For example:
Col1
1
2
3
4
5
6
a
b
Becomes:
Col1
1
2
3
4
5
6
However, I have discovered that if I manually go into the excel sheet and convert the entire table cell format to "Text", this issue is resolved. However, doing this converts any dates in that excel sheet into unrecognizable strings of numbers, so I want to avoid doing this if at all possible.
For example: 7/2/2020 becomes 44014 if converted to "Text".
Here is my new code:
private void Something()
{
if (ofd.ShowDialog() == DialogResult.OK)
{
PathName = ofd.FileName;
FileName = System.IO.Path.GetFileNameWithoutExtension(ofd.FileName);
strConn = string.Empty;
FileInfo file = new FileInfo(PathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
}
using (OleDbConnection cn = new OleDbConnection { ConnectionString = ConnectionString(PathName, "No") })
{
using (OleDbCommand cmd = new OleDbCommand { CommandText = query, Connection = cn })
{
cn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
dtDataTable.Load(dr);
}
}
dataGridView1.DataSource = dtDataTable;
}
public string ConnectionString(string FileName, string Header)
{
OleDbConnectionStringBuilder Builder = new OleDbConnectionStringBuilder();
if (Path.GetExtension(FileName).ToUpper() == ".XLS")
{
Builder.Provider = "Microsoft.Jet.OLEDB.4.0";
Builder.Add("Extended Properties", string.Format("Excel 8.0;IMEX=1;HDR=Yes;", Header));
}
else
{
Builder.Provider = "Microsoft.ACE.OLEDB.12.0";
Builder.Add("Extended Properties", string.Format("Excel 12.0;IMEX=1;HDR=Yes;", Header));
}
Builder.DataSource = FileName;
return Builder.ConnectionString;
}
OleDb Objects
Actually what I meant is, to get formatted/trimmed string values from the Excel Sheet and create a DataTable with DataColumn objects of string type only, use the forward-only OleDbDataReader to create both, DataColumn and DataRow objects as it reads. Doing so, the data will be modified and filled in one step hence no need to call another routine to loop again and waste some more time. Also, consider using asynchronous calls to speed up the process and avoid freezing the UI while executing the lengthy task.
Something might help you to go:
private async void TheCaller()
{
using (var ofd = new OpenFileDialog
{
Title = "Select File",
Filter = "Excel WorkBook|*.xlsx|Excel WorkBook 97 - 2003|*.xls|All Files(*.*)|*.*",
AutoUpgradeEnabled = true,
})
{
if (ofd.ShowDialog() != DialogResult.OK) return;
var conString = string.Empty;
var msg = "Loading... Please wait.";
try
{
switch (ofd.FilterIndex)
{
case 1: //xlsx
conString = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={ofd.FileName};Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
case 2: //xls
conString = $"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={ofd.FileName};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
default:
throw new FileFormatException();
}
var sheetName = "sheet1";
var dt = new DataTable();
//Optional: a label to show the current status
//or maybe show a ProgressBar with ProgressBarStyle = Marquee
lblStatus.Text = msg;
await Task.Run(() =>
{
using (var con = new OleDbConnection(conString))
using (var cmd = new OleDbCommand($"SELECT * From [{sheetName}$]", con))
{
con.Open();
using (var r = cmd.ExecuteReader())
while (r.Read())
{
if (dt.Columns.Count == 0)
for (var i = 0; i < r.FieldCount; i++)
dt.Columns.Add(r.GetName(i).Trim(), typeof(string));
object[] values = new object[r.FieldCount];
r.GetValues(values);
dt.Rows.Add(values.Select(x => x?.ToString().Trim()).ToArray());
}
}
});
//If you want...
dataGridView1.DataSource = null;
dataGridView1.DataSource = dt;
msg = "Loading Completed";
}
catch (FileFormatException)
{
msg = "Unknown Excel file!";
}
catch (Exception ex)
{
msg = ex.Message;
}
finally
{
lblStatus.Text = msg;
}
}
}
Here's a demo, reading sheets with 8 columns and 5000 rows from both xls and xlsx files:
Less than a second. Not bad.
However, this will not work correctly if the Sheet has mixed-types columns like your case where the third column has string and int values in different rows. That because the data type of a column is guessed in Excel by examining the first 8 rows by default. Changing this behavior requires changing the registry value of TypeGuessRows in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\x.0\Engines\Excel from 8 to 0 to force checking all the rows instead of just the first 8. This action will dramatically slow down the performance.
Office Interop Objects
Alternatively, you could use the Microsoft.Office.Interop.Excel objects to read the Excel Sheet, get and format the values of the cells regardless of their types.
using Excel = Microsoft.Office.Interop.Excel;
//...
private async void TheCaller()
{
using (var ofd = new OpenFileDialog
{
Title = "Select File",
Filter = "Excel WorkBook|*.xlsx|Excel WorkBook 97 - 2003|*.xls|All Files(*.*)|*.*",
AutoUpgradeEnabled = true,
})
{
if (ofd.ShowDialog() != DialogResult.OK) return;
var msg = "Loading... Please wait.";
Excel.Application xlApp = null;
Excel.Workbook xlWorkBook = null;
try
{
var dt = new DataTable();
lblStatus.Text = msg;
await Task.Run(() =>
{
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(ofd.FileName, Type.Missing, true);
var xlSheet = xlWorkBook.Sheets[1] as Excel.Worksheet;
var xlRange = xlSheet.UsedRange;
dt.Columns.AddRange((xlRange.Rows[xlRange.Row] as Excel.Range)
.Cells.Cast<Excel.Range>()
.Where(h => h.Value2 != null)
.Select(h => new DataColumn(h.Value2.ToString()
.Trim(), typeof(string))).ToArray());
foreach (var r in xlRange.Rows.Cast<Excel.Range>().Skip(1))
dt.Rows.Add(r.Cells.Cast<Excel.Range>()
.Take(dt.Columns.Count)
.Select(v => v.Value2 is null
? string.Empty
: v.Value2.ToString().Trim()).ToArray());
});
(dataGridView1.DataSource as DataTable)?.Dispose();
dataGridView1.DataSource = null;
dataGridView1.DataSource = dt;
msg = "Loading Completed";
}
catch (FileFormatException)
{
msg = "Unknown Excel file!";
}
catch (Exception ex)
{
msg = ex.Message;
}
finally
{
xlWorkBook?.Close(false);
xlApp?.Quit();
Marshal.FinalReleaseComObject(xlWorkBook);
Marshal.FinalReleaseComObject(xlApp);
xlWorkBook = null;
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
lblStatus.Text = msg;
}
}
}
Note: You need to add reference to the mentioned library.
Not fast especially with a big number of cells but it gets the desired output.

How to open multiselected files on Datagridview in C#

I have alot of excel files I want to selecte Three files and show them in datagridview, I tried with code but my code show only the last one,e.g I have 1,2,3 files, datagridview show just file 3.
What should I do here please,
enter code here
private void Button2_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "XML Files, Text Files, Excel Files| *.xlsx; *.xls; *.xml; *.txt; "; ;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
//tb_path is textbox
tb_path.Text = file;
// excelFilePath_com = tb_path.Text;
}
string constr = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + tb_path.Text + ";Extended Properties = \"Excel 12.0; HDR=Yes;\"; ");
OleDbConnection con = new OleDbConnection(constr);
con.Open();
drop_down_sheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//dro_down_sheet is combobox to choose which sheet to import
drop_down_sheet.DisplayMember = "TABLE_NAME";
drop_down_sheet.ValueMember = "TABLE_NAME";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,
"Important Note",
MessageBoxButtons.OK,
MessageBoxIcon.Error,
MessageBoxDefaultButton.Button1);
}
}
If I understand your code well, you are looping through all openFileDialog1.FileNames before doing anything with them. If you encapsulate everything in your foreach loop, you should be able to use all selected files. For example:
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
//tb_path is textbox
tb_path.Text = file;
// excelFilePath_com = tb_path.Text;
string constr = string.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source =" + tb_path.Text + ";Extended Properties = \"Excel 12.0; HDR=Yes;\"; ");
OleDbConnection con = new OleDbConnection(constr);
con.Open();
drop_down_sheet.DataSource = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
//dro_down_sheet is combobox to choose which sheet to import
drop_down_sheet.DisplayMember = "TABLE_NAME";
drop_down_sheet.ValueMember = "TABLE_NAME";
}
}

How to upload multiple Excel files in asp.net

This is the 1st table called excel2 for storing English characters
This is the 2nd table called excel3 for storing numbers
For the Excel file, there's two sheet in total, the first sheet store data of English characters and the second sheet store data of numbers.
User can choose to import multiple Excel files at the same time.
Now, when user select 3 excel file, the foreach loop is looping 3 times, but the data being inserted to the database only contain data from the 1st excel file repeatedly.
Any idea? Many thanks
public partial class multipleexcelimport : System.Web.UI.Page
{
protected void importfile()
{
String MyConString = "SERVER=localhost;" + "DATABASE=mysql_testing;" + "UID=root;" + "PASSWORD=tammy;SslMode=none";
if (this.uploadfile.HasFile)
{
string[] segments = fn.Split('.');
string fileExt = segments[segments.Length - 1];
if (fileExt != "xlsx")
{
showMessage("輸入錯誤", "請上傳正確檔案xlsx");
return;
}
foreach (var file in uploadfile.PostedFiles)
{
var fn = file.FileName;
string newfileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fn;
string filepath = Server.MapPath(ConfigurationSettings.AppSettings["UPLOAD_FOLDER"]) + newfileName;
this.uploadfile.SaveAs(filepath);
ExcelPackage xlWorkbook = new ExcelPackage(new FileInfo(filepath));
ExcelWorksheet xlRange = xlWorkbook.Workbook.Worksheets[1];
int rowCount = xlRange.Dimension.End.Row;
ExcelWorksheet xlRange2 = xlWorkbook.Workbook.Worksheets[2];
int rowCount2 = xlRange2.Dimension.End.Row;
string sql = "";
string linkid = "";
MySqlConnection conn = null;
MySqlDataAdapter msda = null;
DataSet ds = null;
List<string> FailList = new List<string>();
conn = new MySqlConnection(MyConString);
DateTime dTime = DateTime.Now;
string now_time = dTime.ToString("yyyy-MM-dd HH:mm:ss");
conn.Open();
conn.Close();
using (TransactionScope scope = new TransactionScope())
{
try
{
conn.Open();
//sheet1
for (int i = 2; i <= rowCount; i++)
{
string dates = xlRange.Cells[i, 1].Value.ToString();
sql = "INSERT INTO mysql_testing.excel2 set"
+ " excel = ?dates;"
ds = new DataSet();
msda = new MySqlDataAdapter(sql, conn);
msda.SelectCommand.Parameters.AddWithValue("dates", dates);
}
//sheet2
for (int i = 2; i <= rowCount2; i++)
{
string excel3 = xlRange2.Cells[i, 1].Value.ToString();
sql = "INSERT INTO mysql_testing.excel3 set"
+ " excel3 = ?excel3;" ;
ds = new DataSet();
msda = new MySqlDataAdapter(sql, conn);
msda.SelectCommand.Parameters.AddWithValue("excel3", excel3);
}
showMessage("alert", "success");
scope.Complete();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "tab", "$('.nav-tabs a[href=\"#massimport\"]').tab('show')", true);
}
}
else
{
showMessage("error", "select file plz");
ScriptManager.RegisterStartupScript(this, this.GetType(), "tab", "$('.nav-tabs a[href=\"#massimport\"]').tab('show')", true);
}
}
public void showMessage(string title, string content)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + content + "');", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
importfile();
}
}

How To insert data into SQL Sever with C# without using the database wizard(visual studio)

I'm having trouble inserting data into my table called "client" in my database called "vet".
I'm trying to do the connection manually as opposed to using the database wizard. I want to do it this way so that i can hide the majority of my code in a separate class.
I have a feeling I have the logic for this all wrong as I'm not making use of a data set, I was hoping someone could point me in the right direction.
This is for a school assignment and not for real world use. I have read a number of similar posts but am still unable to come to a solution.
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
DataSet ds = new DataSet();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = ds.Tables["client"].NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
A DataSet is a collection of DataTables. In your example, you're only referring to one table. The SqlDataAdapter.Fill method will populate either DataSet or DataTable. You're calling da.Fill(client) which is fine - it will fill the DataTable client. You could also call da.Fill(ds, "client") which will fill the DataSet ds. You can then extract your table via ds.Tables["client"]. Using a DataSet in this example is overkill, but you can show your tutor how a DataSet works.
You're filling the DataTable but then adding the new row with reference to the DataSet. But in your example, the DataSet ds has nothing in it, because you filled the DataTable not the DataSet. Try this:
DataSet ds = new DataSet();
string commandString = "SELECT TOP 0 * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
da.Fill(ds, "client");
DataTable client = ds.Tables["client"];
DataRow newClientRow = client.NewRow();
... ... ...
client.Rows.Add(newClientRow);
builder.GetInsertCommand();
da.Update(client);
If you only want to insert a row, you don't need to SELECT all the rows. If you SELECT TOP 0 * from client you'll get the column names (which you need) but without the overhead of returning all the rows.
Try something like this:
public void CommitToDatabase()
{
using (var con = new SqlConnection(CLSDatabaseDetails.GlobalConnectionString))
{
DataTable client = new DataTable();
string commandString = "SELECT * FROM client";
SqlCommand cmd = new SqlCommand(commandString, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(client);
DataRow newClientRow = client.NewRow();
newClientRow["ClientID"] = ClientID;
newClientRow["FirstName"] = FirstName;
newClientRow["LastName"] = LastName;
newClientRow["Phone"] = PhoneNumber;
newClientRow["CAddress"] = Address;
newClientRow["Email"] = Email;
newClientRow["CUsername"] = Username;
newClientRow["CPassword"] = Password;
client.Rows.Add(newClientRow);
da.Update(client);
}
}
I can't tell what the source of your data is. Anyway, here are two examples of moving data from a CSV file to SQL Server and from a DataGridView to SQL Server.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.IO;
using Microsoft.VisualBasic.FileIO;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Configuration;
public class Form1
{
private void Button1_Click(System.Object sender, System.EventArgs e)
{
dynamic headers = (from header in DataGridView1.Columns.Cast<DataGridViewColumn>()header.HeaderText).ToArray;
dynamic rows = from row in DataGridView1.Rows.Cast<DataGridViewRow>()where !row.IsNewRowArray.ConvertAll(row.Cells.Cast<DataGridViewCell>.ToArray, c => c.Value != null ? c.Value.ToString : "");
string str = "";
using (IO.StreamWriter sw = new IO.StreamWriter("C:\\Users\\Excel\\Desktop\\OrdersTest.csv")) {
sw.WriteLine(string.Join(",", headers));
//sw.WriteLine(String.Join(","))
foreach (void r_loopVariable in rows) {
r = r_loopVariable;
sw.WriteLine(string.Join(",", r));
}
sw.Close();
}
}
private void Button2_Click(System.Object sender, System.EventArgs e)
{
//Dim m_strConnection As String = "server='Server_Name';Initial Catalog='Database_Name';Trusted_Connection=True;"
//Catch ex As Exception
// MessageBox.Show(ex.ToString())
//End Try
//Dim objDataset1 As DataSet()
//Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
//Dim da As OdbcDataAdapter
System.Windows.Forms.OpenFileDialog OpenFile = new System.Windows.Forms.OpenFileDialog();
// Does something w/ the OpenFileDialog
string strFullPath = null;
string strFileName = null;
TextBox tbFile = new TextBox();
// Sets some OpenFileDialog box options
OpenFile.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";
// Shows only .csv files
OpenFile.Title = "Browse to file:";
// Title at the top of the dialog box
// Makes the open file dialog box show up
if (OpenFile.ShowDialog() == DialogResult.OK) {
strFullPath = OpenFile.FileName;
// Assigns variable
strFileName = Path.GetFileName(strFullPath);
// Checks to see if they've picked a file
if (OpenFile.FileNames.Length > 0) {
tbFile.Text = strFullPath;
// Puts the filename in the textbox
// The connection string for reading into data connection form
string connStr = null;
connStr = "Driver={Microsoft Text Driver (*.txt; *.csv)}; Dbq=" + Path.GetDirectoryName(strFullPath) + "; Extensions=csv,txt ";
// Sets up the data set and gets stuff from .csv file
OdbcConnection Conn = new OdbcConnection(connStr);
DataSet ds = default(DataSet);
OdbcDataAdapter DataAdapter = new OdbcDataAdapter("SELECT * FROM [" + strFileName + "]", Conn);
ds = new DataSet();
try {
DataAdapter.Fill(ds, strFileName);
// Fills data grid..
DataGridView1.DataSource = ds.Tables(strFileName);
// ..according to data source
// Catch and display database errors
} catch (OdbcException ex) {
OdbcError odbcError = default(OdbcError);
foreach ( odbcError in ex.Errors) {
MessageBox.Show(ex.Message);
}
}
// Cleanup
OpenFile.Dispose();
Conn.Dispose();
DataAdapter.Dispose();
ds.Dispose();
}
}
}
private void Button3_Click(System.Object sender, System.EventArgs e)
{
SqlConnection cnn = default(SqlConnection);
string connectionString = null;
string sql = null;
connectionString = "data source='Server_Name';" + "initial catalog='Database_Name';Trusted_Connection=True";
cnn = new SqlConnection(connectionString);
cnn.Open();
sql = "SELECT * FROM [Order Details]";
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
DataGridView1.DataSource = ds.Tables(0);
cnn.Close();
}
private void ProductsDataGridView_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == DataGridView1.Columns(3).Index && e.Value != null) {
//
if (Convert.ToInt32(e.Value) < 10) {
e.CellStyle.BackColor = Color.OrangeRed;
e.CellStyle.ForeColor = Color.LightGoldenrodYellow;
}
//
}
//
}
//Private Sub ProductsDataGridView_CellFormatting(ByVal sender As Object, _
// ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
// Handles DataGridView1.CellFormatting
// '
// If e.ColumnIndex = DataGridView1.Columns("DataGridViewTextBoxColumn8").Index _
// AndAlso e.Value IsNot Nothing Then
// '
// If CInt(e.Value) < 5 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
// '
// End If
// '
//End Sub
//If e.ColumnIndex = ProductsDataGridView.Columns(4).Index _
//AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
// ''To (you need to change the column name)
// If e.ColumnIndex = ProductsDataGridView.Columns("YourColumnName").Index _
// AndAlso e.Value IsNot Nothing Then
//'
// If CInt(e.Value) = 0 Then
// e.CellStyle.BackColor = Color.OrangeRed
// e.CellStyle.ForeColor = Color.LightGoldenrodYellow
// End If
//End If
private void Button4_Click(System.Object sender, System.EventArgs e)
{
DataTable tblReadCSV = new DataTable();
tblReadCSV.Columns.Add("FName");
tblReadCSV.Columns.Add("LName");
tblReadCSV.Columns.Add("Department");
TextFieldParser csvParser = new TextFieldParser("C:\\Users\\Excel\\Desktop\\Employee.txt");
csvParser.Delimiters = new string[] { "," };
csvParser.TrimWhiteSpace = true;
csvParser.ReadLine();
while (!(csvParser.EndOfData == true)) {
tblReadCSV.Rows.Add(csvParser.ReadFields());
}
SqlConnection con = new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;");
string strSql = "Insert into Employee(FName,LName,Department) values(#Fname,#Lname,#Department)";
//Dim con As New SqlConnection(strCon)
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql;
cmd.Connection = con;
cmd.Parameters.Add("#Fname", SqlDbType.VarChar, 50, "FName");
cmd.Parameters.Add("#Lname", SqlDbType.VarChar, 50, "LName");
cmd.Parameters.Add("#Department", SqlDbType.VarChar, 50, "Department");
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.InsertCommand = cmd;
int result = dAdapter.Update(tblReadCSV);
}
private void Button5_Click(System.Object sender, System.EventArgs e)
{
string SQLConnectionString = "Data Source=Excel-PC\\SQLEXPRESS;" + "Initial Catalog=Northwind;" + "Trusted_Connection=True";
// Open a connection to the AdventureWorks database.
using (SqlConnection SourceConnection = new SqlConnection(SQLConnectionString)) {
SourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand CommandRowCount = new SqlCommand("SELECT COUNT(*) FROM dbo.Orders;", SourceConnection);
long CountStart = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", CountStart);
// Get data from the source table as a AccessDataReader.
//Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
// "Data Source=" & "C:\Users\Excel\Desktop\OrdersTest.txt" & ";" & _
// "Extended Properties=" & "text;HDR=Yes;FMT=Delimited"","";"
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + "C:\\Users\\Excel\\Desktop\\" + ";" + "Extended Properties=\"Text;HDR=No\"";
System.Data.OleDb.OleDbConnection TextConnection = new System.Data.OleDb.OleDbConnection(ConnectionString);
OleDbCommand TextCommand = new OleDbCommand("SELECT * FROM OrdersTest#csv", TextConnection);
TextConnection.Open();
OleDbDataReader TextDataReader = TextCommand.ExecuteReader(CommandBehavior.SequentialAccess);
// Open the destination connection.
using (SqlConnection DestinationConnection = new SqlConnection(SQLConnectionString)) {
DestinationConnection.Open();
// Set up the bulk copy object.
// The column positions in the source data reader
// match the column positions in the destination table,
// so there is no need to map columns.
using (SqlBulkCopy BulkCopy = new SqlBulkCopy(DestinationConnection)) {
BulkCopy.DestinationTableName = "dbo.Orders";
try {
// Write from the source to the destination.
BulkCopy.WriteToServer(TextDataReader);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
} finally {
// Close the AccessDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the Using block.
TextDataReader.Close();
}
}
// Perform a final count on the destination table
// to see how many rows were added.
long CountEnd = System.Convert.ToInt32(CommandRowCount.ExecuteScalar());
//Console.WriteLine("Ending row count = {0}", CountEnd)
//Console.WriteLine("{0} rows were added.", CountEnd - CountStart)
}
}
//Dim FILE_NAME As String = "C:\Users\Excel\Desktop\OrdersTest.csv"
//Dim TextLine As String
//If System.IO.File.Exists(FILE_NAME) = True Then
// Dim objReader As New System.IO.StreamReader(FILE_NAME)
// Do While objReader.Peek() <> -1
// TextLine = TextLine & objReader.ReadLine() & vbNewLine
// Loop
//Else
// MsgBox("File Does Not Exist")
//End If
//Dim cn As New SqlConnection("Data Source=Excel-PC\SQLEXPRESS;Initial Catalog=Northwind;Trusted_Connection=True;")
//Dim cmd As New SqlCommand
//cmd.Connection = cn
//cmd.Connection.Close()
//cmd.Connection.Open()
//cmd.CommandText = "INSERT INTO Orders (OrderID,CustomerID,EmployeeID,OrderDate,RequiredDate,ShippedDate,ShipVia,Freight,ShipName,ShipAddress,ShipCity,ShipRegion,ShipPostalCode,ShipCountry) values & OrdersTest.csv"
//cmd.ExecuteNonQuery()
//cmd.Connection.Close()
}
private void Button6_Click(System.Object sender, System.EventArgs e)
{
// Define the Column Definition
DataTable dt = new DataTable();
dt.Columns.Add("OrderID", typeof(int));
dt.Columns.Add("CustomerID", typeof(string));
dt.Columns.Add("EmployeeID", typeof(int));
dt.Columns.Add("OrderDate", typeof(System.DateTime));
dt.Columns.Add("RequiredDate", typeof(System.DateTime));
dt.Columns.Add("ShippedDate", typeof(System.DateTime));
dt.Columns.Add("ShipVia", typeof(int));
dt.Columns.Add("Freight", typeof(decimal));
dt.Columns.Add("ShipName", typeof(string));
dt.Columns.Add("ShipAddress", typeof(string));
dt.Columns.Add("ShipCity", typeof(string));
dt.Columns.Add("ShipRegion", typeof(string));
dt.Columns.Add("ShipPostalCode", typeof(string));
dt.Columns.Add("ShipCountry", typeof(string));
using (cn == new SqlConnection("Server='Server_Name';Database='Database_Name';Trusted_Connection=True;")) {
cn.Open();
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser("C:\\Users\\Excel\\Desktop\\OrdersTest.csv");
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = dt.NewRow();
for (currColumn = 0; currColumn <= dt.Columns.Count - 1; currColumn++) {
sqlColumnDataType = dt.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
dt.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
//Return False
} finally {
dr = null;
}
}
using (SqlBulkCopy copy = new SqlBulkCopy(cn)) {
copy.DestinationTableName = "[dbo].[Orders]";
copy.WriteToServer(dt);
}
}
}
public static bool GetCsvData(string CSVFileName, ref DataTable CSVTable)
{
Microsoft.VisualBasic.FileIO.TextFieldParser reader = default(Microsoft.VisualBasic.FileIO.TextFieldParser);
string[] currentRow = null;
DataRow dr = default(DataRow);
string sqlColumnDataType = null;
reader = My.Computer.FileSystem.OpenTextFieldParser(CSVFileName);
reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
reader.Delimiters = new string[] { "," };
while (!reader.EndOfData) {
try {
currentRow = reader.ReadFields();
dr = CSVTable.NewRow();
for (currColumn = 0; currColumn <= CSVTable.Columns.Count - 1; currColumn++) {
sqlColumnDataType = CSVTable.Columns(currColumn).DataType.Name;
switch (sqlColumnDataType) {
case "String":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToString(currentRow(currColumn));
}
break;
case "Decimal":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = 0;
} else {
dr.Item(currColumn) = Convert.ToDecimal(currentRow(currColumn));
}
break;
case "DateTime":
if (string.IsNullOrEmpty(currentRow(currColumn))) {
dr.Item(currColumn) = "";
} else {
dr.Item(currColumn) = Convert.ToDateTime(currentRow(currColumn));
}
break;
}
}
CSVTable.Rows.Add(dr);
} catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex) {
Interaction.MsgBox("Line " + ex.Message + "is not valid." + Constants.vbCrLf + "Terminating Read Operation.");
reader.Close();
reader.Dispose();
return false;
} finally {
dr = null;
}
}
reader.Close();
reader.Dispose();
return true;
}
}
//=======================================================
//Service provided by Telerik (www.telerik.com)
//Conversion powered by NRefactory.
//Twitter: #telerik
//Facebook: facebook.com/telerik
//=======================================================

How To Update an Excel File From a Gridview Row in ASP.NET (C#)?

I am attempting a simple program. When the user clicks the button, the value of TextBox1 is run against a stored proc, returning a Customer ID. That Customer ID is looked up in an Excel sheet. If found, the information for the corresponding row is bound to a Gridview. However, once this is done, I would like to write THAT row to the second sheet of the excel file the info was pulled from. The code is a bit messy, as I'm trying a few different things in the process.
Currently the Excel file is saved, but of course the row that is currently there, is overwritten, so there will always be just one row.
What is the cleanest, easiest way to update (or insert) the data from a Gridview (only holding one row) to a sheet on an Excel file? Basically, this will be done over and over (when a user inputs a number and clicks the event button) so rows in the second sheet (Sheet2) will continually be updated from the Gridview. Any help is appreciated. I apologize if this sounds/looks amateurish.
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != "")
{
DateTime saveNow = DateTime.Now;
long numCardNumber;
string strCardNumber; // Card number (stored as string)
char[] MyChar = { ';', '?' }; // array with 2 char
string customerID; //holds the customer ID returned by the stored proc CNBID
int CustID = 0; //Customer_id returned from stored proc CNBID
int incrementByOne; //Used to increment number of cards scanned Application level variable
//Create local label and assign text -> Site.Master lblTimeStamp
Label lblTimeStampLocal = (Label)Master.FindControl("lblTimeStamp");
Label lblScannedLocal = (Label)Master.FindControl("lblScanned");
//Cleanup input
strCardNumber = TextBox1.Text.TrimEnd(MyChar); // Trims end
strCardNumber = strCardNumber.TrimStart(MyChar); //Trims beginning
lbliMAG.Text = strCardNumber;
lblYourNumber.Visible = false; //if previously displayed, turns the label off
try //try and convert the string to a number (if valid numerical characters
{
numCardNumber = Convert.ToInt64(strCardNumber);
}
catch (FormatException) // thrown if input characters are not valid numeric
{
lblYourNumber.Visible = true;
GridView1.Visible = false;
lblQualify.Visible = false;
lblYourNumber.Text = "NOT A VALID CARD NUMBER!";
TextBox1.Focus();
return;
}
try //try and convert the string to a number (if valid numerical characters
{
string connectionInfo = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLConn"]);
SqlConnection connection = new SqlConnection(connectionInfo);
connection.Open();
SqlCommand cmd = new SqlCommand("CNBID", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("#iMAG", SqlDbType.Char, 18); //#iMAG parameter
param.Direction = ParameterDirection.Input;
param.Value = strCardNumber; //Sets the parameter to the value of the scanned card (after trimmed characters)
try
{
CustID = (int)cmd.ExecuteScalar(); //returns int to customerID if card # found
}
catch
{
lblYourNumber.Visible = true;
GridView1.Visible = false;
lblQualify.Visible = false;
lblYourNumber.Text = "NOT A VALID CARD NUMBER!";
TextBox1.Focus();
return;
}
TextBox1.Text = ""; //resets TextBox1;
connection.Close();
}
catch (FormatException) // thrown if input characters are not valid numeric
{
lblYourNumber.Visible = true;
GridView1.Visible = false;
lblQualify.Visible = false;
lblYourNumber.Text = "NOT A VALID CARD NUMBER!";
TextBox1.Focus();
return;
}
//if (customerID != null)
if (CustID != 0)
{
lblCustID.Text = Convert.ToString(CustID); //assigns customerID to stat label
}
else
{
lblYourNumber.Visible = true;
GridView1.Visible = false;
lblQualify.Visible = false;
lblYourNumber.Text = "Customer Not Found!";
}
//string connString = ConfigurationManager.ConnectionStrings["xls"].ConnectionString;
string Excel = Server.MapPath("App_Data\\CNB.xls");
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Excel + ";Extended Properties=Excel 8.0;";
//txtReturn.Text = connString; (//shows the connection string
// Create the connection object
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
// Create OleDbCommand object and select data from worksheet Sheet1
string ExcelConn = "SELECT custid,first,last,addr1,addr2,city,state,zip FROM [Sheet1$] WHERE custid=" + CustID;
OleDbCommand cmd2 = new OleDbCommand(ExcelConn, oledbConn);
// Create new OleDbDataAdapter
OleDbDataAdapter oleda = new OleDbDataAdapter(); //OleDbDataAdapter.SelectCommand
oleda.SelectCommand = cmd2;
// Create a DataSet which will hold the data extracted from the worksheet.
DataSet ds = new DataSet();
//DataTable dt = new DataTable();
// Fill the DataSet from the data extracted from the worksheet.
oleda.Fill(ds, "Processed Customer");
if (ds.Tables[0].Rows.Count != 0)
{
// Bind the data to the GridView
lblCol1.Text = ds.Tables[0].Columns[0].ColumnName;
GridView1.DataSource = ds.Tables[0].Columns[0].ColumnName = " Customer ID ";
GridView1.DataSource = ds.Tables[0].Columns[1].ColumnName = " First Name ";
GridView1.DataSource = ds.Tables[0].Columns[2].ColumnName = " Last Name ";
GridView1.DataSource = ds.Tables[0].Columns[3].ColumnName = " Address 1 ";
GridView1.DataSource = ds.Tables[0].Columns[4].ColumnName = " Address 2 ";
GridView1.DataSource = ds.Tables[0].Columns[5].ColumnName = " City ";
GridView1.DataSource = ds.Tables[0].Columns[6].ColumnName = " Province / State ";
GridView1.DataSource = ds.Tables[0].Columns[7].ColumnName = " Postal Code / Zip ";
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
GridView1.Visible = true; // SHows the GridView after it populates
lblQualify.Visible = true;
lblQualify.Text = "Customer Qualifies!";
TextBox1.Focus();
incrementByOne = (int)Application["numberofTimesScanned"] + 1;
Application["numberofTimesScanned"] = incrementByOne;
lblTimeStampLocal.Text = "Last Scan: " + Convert.ToString(saveNow);
lblScannedLocal.Text = "Number Of Scans Completed: " + Convert.ToString(Application["numberofTimesScanned"]);
// Saves Excel document
var wb = new XLWorkbook();
wb.Worksheets.Add(ds);
wb.SaveAs(Server.MapPath("App_Data\\CustomersProcessed.xlsx"));
TextBox1.Focus();
try
{
cmd2 = new OleDbCommand("INSERT INTO [Sheet2$] (CustID, FirstName) VALUES ('1123', 'Homer')", oledbConn);
oleda.InsertCommand = cmd2;
}
catch (Exception error)
{
lblYourNumber.Text = error.Message;
}
}
else
{
lblQualify.Text = "Customer Does Not Qualify!";
GridView1.Visible = false; // Hides the Gridview
TextBox1.Focus();
}
}
catch (Exception error)
{
lblYourNumber.Visible = true;
GridView1.Visible = false;
lblQualify.Visible = false;
lblYourNumber.Text = error.Message;
}
finally
{
// Close connection
oledbConn.Close();
}
} //END IF
else
{
lblYourNumber.Visible = true;
lblYourNumber.Text = "NO CARD NUMBER SUBMITTED!";
}
}
I ended up just using the following:
using (DbCommand command = oledbConn.CreateCommand())
{
command.CommandText = "INSERT INTO [Sheet2$] (custid, Fullname, Salutation) VALUES (" + CustID + ",\"John Smith\",\"John\")";
//connection.Open();
command.ExecuteNonQuery();
}
That did the trick. :-)

Categories

Resources