Here is my case: i can retrieved the data from the database, but when i run the program and filled up the Quantity column (on the third line), the error says: index was out of range. Anyone know why is this happen? (When i tried to fill the Quantity column (on third line), the error appeared) <-- shown in the picture below.
Here is the images of my program:
Here is the images of where the error is pointed:
Here is the full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
namespace Sell_System
{
public partial class Form2 : Form
{
string connectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\Archives\Projects\Program\Sell System\Sell System\App_Data\db1.accdb;Persist Security Info=False;");
private Form1 firstForm;
private List<List<TextBox>> textBoxCodeContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxQuantityContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxDescContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxSubTotalContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxTotalContainer = new List<List<TextBox>>();
private List<List<TextBox>> textBoxAllTotalContainer = new List<List<TextBox>>();
public Form2()
{
InitializeComponent();
}
public Form2(Form1 firstForm)
: this()
{
this.firstForm = firstForm;
}
private void Form2_Load(object sender, EventArgs e)
{
UpdateTextPosition();
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT [Code] FROM [Data]", conn);
dReader = cmd.ExecuteReader();
AutoCompleteStringCollection codesCollection = new AutoCompleteStringCollection();
while (dReader.Read())
{
string numString = dReader[0].ToString().PadLeft(4, '0');
codesCollection.Add(numString);
}
dReader.Close();
conn.Close();
if (firstForm.comboBox1.SelectedIndex == 0)
{
label1.Text = "Code:";
label1.Location = new Point(60, 125);
label2.Text = "Welcome to the Selling System.";
label2.Location = new Point(600, 0);
label3.Text = "Quantity:";
label3.Location = new Point(155, 125);
label4.Text = "Description:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total on Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total on Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total on Rp:";
label7.Location = new Point(1080, 580);
}
else if (firstForm.comboBox1.SelectedIndex == 1)
{
label1.Text = "Kode:";
label1.Location = new Point(60, 125);
label2.Text = "Selamat datang di Selling System.";
label2.Location = new Point(600, 0);
label3.Text = "Banyaknya:";
label3.Location = new Point(145, 125);
label4.Text = "Keterangan:";
label4.Location = new Point(580, 125);
label5.Text = "Sub Total di Rp:";
label5.Location = new Point(1020, 125);
label6.Text = "Total di Rp:";
label6.Location = new Point(1210, 125);
label7.Text = "Total di Rp:";
label7.Location = new Point(1080, 580);
}
//****TextBox for Code****
for (int y = 0; y <= 16; y++)
{
textBoxCodeContainer.Add(new List<TextBox>());
textBoxCodeContainer[0].Add(new TextBox());
textBoxCodeContainer[0][y].Size = new Size(100, 50);
textBoxCodeContainer[0][y].Location = new Point(25, 150 + (y * 25));
textBoxCodeContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
textBoxCodeContainer[0][y].AutoCompleteMode = AutoCompleteMode.Suggest;
textBoxCodeContainer[0][y].AutoCompleteSource = AutoCompleteSource.CustomSource;
textBoxCodeContainer[0][y].AutoCompleteCustomSource = codesCollection;
Controls.Add(textBoxCodeContainer[0][y]);
}
//****TextBox for Quantity****
for (int y = 0; y <= 16; y++)
{
textBoxQuantityContainer.Add(new List<TextBox>());
textBoxQuantityContainer[0].Add(new TextBox());
textBoxQuantityContainer[0][y].Size = new Size(100, 50);
textBoxQuantityContainer[0][y].Location = new Point(125, 150 + (y * 25));
textBoxQuantityContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxQuantityContainer[0][y]);
}
//****TextBox for Description****
for (int y = 0; y <= 16; y++)
{
textBoxDescContainer.Add(new List<TextBox>());
textBoxDescContainer[0].Add(new TextBox());
textBoxDescContainer[0][y].Size = new Size(750, 50);
textBoxDescContainer[0][y].Location = new Point(225, 150 + (y * 25));
Controls.Add(textBoxDescContainer[0][y]);
}
//****TextBox for Sub Total****
for (int y = 0; y <= 16; y++)
{
textBoxSubTotalContainer.Add(new List<TextBox>());
textBoxSubTotalContainer[0].Add(new TextBox());
textBoxSubTotalContainer[0][y].Size = new Size(175, 50);
textBoxSubTotalContainer[0][y].Location = new Point(975, 150 + (y * 25));
Controls.Add(textBoxSubTotalContainer[0][y]);
}
//****TextBox for Total****
for (int y = 0; y <= 16; y++)
{
textBoxTotalContainer.Add(new List<TextBox>());
textBoxTotalContainer[0].Add(new TextBox());
textBoxTotalContainer[0][y].Size = new Size(175, 50);
textBoxTotalContainer[0][y].Location = new Point(1150, 150 + (y * 25));
textBoxTotalContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxTotalContainer[0][y]);
}
//****TextBox for Total All****
textBoxAllTotalContainer.Size = new Size(175, 50);
textBoxAllTotalContainer.Location = new Point(1150, 575);
textBoxAllTotalContainer.TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxAllTotalContainer);
}
private void UpdateTextPosition()
{
Graphics g = this.CreateGraphics();
Double startingPoint = (this.Width / 2) - (g.MeasureString(this.Text.Trim(), this.Font).Width / 2);
Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
String tmp = " ";
Double tmpWidth = 0;
while ((tmpWidth + widthOfASpace) < startingPoint)
{
tmp += " ";
tmpWidth += widthOfASpace;
}
this.Text = tmp + this.Text.Trim();
}
private void UpdateDatas()
{
int codeValue = 0;
int index = 0;
string query = "SELECT [Description], [Price] FROM [Data] WHERE [Code] IN (";
OleDbDataReader dReader;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
if (int.TryParse(this.textBoxCodeContainer[0][0].Text, out codeValue))
{
query = query + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][1].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][2].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][3].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][4].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][5].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][6].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][7].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][8].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][9].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][10].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][11].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][12].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][13].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][14].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][15].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
if (int.TryParse(this.textBoxCodeContainer[0][16].Text, out codeValue))
{
query = query + "," + codeValue.ToString();
}
query = query + ")";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("Code", System.Data.OleDb.OleDbType.Integer);
dReader = cmd.ExecuteReader();
while (dReader.Read())
{
if (textBoxCodeContainer[0][index].TextLength != 0)
{
this.textBoxDescContainer[0][index].Text = dReader["Description"].ToString();
this.textBoxSubTotalContainer[0][index].Text = dReader["Price"].ToString();
}
index += 1;
}
dReader.Close();
conn.Close();
}
private void UpdatePrice()
{
if (textBoxQuantityContainer[0][0].Text == "")
{
textBoxTotalContainer[0][0].Text = "";
}
else if (textBoxQuantityContainer[0][0].Text == "1")
{
textBoxTotalContainer[0][0].Text = textBoxSubTotalContainer[0][0].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][0].Text;
}
if (textBoxQuantityContainer[0][1].Text == "")
{
textBoxTotalContainer[0][1].Text = "";
}
else if (textBoxQuantityContainer[0][1].Text == "1")
{
textBoxTotalContainer[0][1].Text = textBoxSubTotalContainer[0][1].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][1].Text;
}
if (textBoxQuantityContainer[0][2].Text == "")
{
textBoxTotalContainer[0][2].Text = "";
}
else if (textBoxQuantityContainer[0][2].Text == "1")
{
textBoxTotalContainer[0][2].Text = textBoxSubTotalContainer[0][2].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][2].Text;
}
if (textBoxQuantityContainer[0][3].Text == "")
{
textBoxTotalContainer[0][3].Text = "";
}
else if (textBoxQuantityContainer[0][3].Text == "1")
{
textBoxTotalContainer[0][3].Text = textBoxSubTotalContainer[0][3].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][3].Text;
}
if (textBoxQuantityContainer[0][4].Text == "")
{
textBoxTotalContainer[0][4].Text = "";
}
else if (textBoxQuantityContainer[0][4].Text == "1")
{
textBoxTotalContainer[0][4].Text = textBoxSubTotalContainer[0][4].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][4].Text;
}
if (textBoxQuantityContainer[0][5].Text == "")
{
textBoxTotalContainer[0][5].Text = "";
}
else if (textBoxQuantityContainer[0][5].Text == "1")
{
textBoxTotalContainer[0][5].Text = textBoxSubTotalContainer[0][5].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][5].Text;
}
if (textBoxQuantityContainer[0][6].Text == "")
{
textBoxTotalContainer[0][6].Text = "";
}
else if (textBoxQuantityContainer[0][6].Text == "1")
{
textBoxTotalContainer[0][6].Text = textBoxSubTotalContainer[0][6].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][6].Text;
}
if (textBoxQuantityContainer[0][7].Text == "")
{
textBoxTotalContainer[0][7].Text = "";
}
else if (textBoxQuantityContainer[0][7].Text == "1")
{
textBoxTotalContainer[0][7].Text = textBoxSubTotalContainer[0][7].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][7].Text;
}
if (textBoxQuantityContainer[0][8].Text == "")
{
textBoxTotalContainer[0][8].Text = "";
}
else if (textBoxQuantityContainer[0][8].Text == "1")
{
textBoxTotalContainer[0][8].Text = textBoxSubTotalContainer[0][8].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][8].Text;
}
if (textBoxQuantityContainer[0][9].Text == "")
{
textBoxTotalContainer[0][9].Text = "";
}
else if (textBoxQuantityContainer[0][9].Text == "1")
{
textBoxTotalContainer[0][9].Text = textBoxSubTotalContainer[0][9].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][9].Text;
}
if (textBoxQuantityContainer[0][10].Text == "")
{
textBoxTotalContainer[0][10].Text = "";
}
else if (textBoxQuantityContainer[0][10].Text == "1")
{
textBoxTotalContainer[0][10].Text = textBoxSubTotalContainer[0][10].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][10].Text;
}
if (textBoxQuantityContainer[0][11].Text == "")
{
textBoxTotalContainer[0][11].Text = "";
}
else if (textBoxQuantityContainer[0][11].Text == "1")
{
textBoxTotalContainer[0][11].Text = textBoxSubTotalContainer[0][11].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][11].Text;
}
if (textBoxQuantityContainer[0][12].Text == "")
{
textBoxTotalContainer[0][12].Text = "";
}
else if (textBoxQuantityContainer[0][12].Text == "1")
{
textBoxTotalContainer[0][12].Text = textBoxSubTotalContainer[0][12].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][12].Text;
}
if (textBoxQuantityContainer[0][13].Text == "")
{
textBoxTotalContainer[0][13].Text = "";
}
else if (textBoxQuantityContainer[0][13].Text == "1")
{
textBoxTotalContainer[0][13].Text = textBoxSubTotalContainer[0][13].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][13].Text;
}
if (textBoxQuantityContainer[0][14].Text == "")
{
textBoxTotalContainer[0][14].Text = "";
}
else if (textBoxQuantityContainer[0][14].Text == "1")
{
textBoxTotalContainer[0][14].Text = textBoxSubTotalContainer[0][14].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][14].Text;
}
if (textBoxQuantityContainer[0][15].Text == "")
{
textBoxTotalContainer[0][15].Text = "";
}
else if (textBoxQuantityContainer[0][15].Text == "1")
{
textBoxTotalContainer[0][15].Text = textBoxSubTotalContainer[0][15].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][15].Text;
}
if (textBoxQuantityContainer[0][16].Text == "")
{
textBoxTotalContainer[0][16].Text = "";
}
else if (textBoxQuantityContainer[0][16].Text == "1")
{
textBoxTotalContainer[0][16].Text = textBoxSubTotalContainer[0][16].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][16].Text;
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
UpdateDatas();
UpdatePrice();
}
}
}
Here is my problem: "i am confuse, when i try assign a value for "textBoxAllTotalContainer.Text = textBoxTotalContainer[0][0].Text", the code is working. but, when i tried "textBoxAllTotalContainer.Text = textBoxTotalContainer[0][one(1)]", the screen stucked in there (I have to stop debugging from Visual Studio)"
textBoxTotalContainer contains 17 textboxes, therefore, i used [0][0] to [0][16], and textBoxAllTotalContainer contains 1 textbox, so i just used textBoxAllTotalContainer.Text
Note: "Keyword (one), it suppose to be "1" <-- number, i wrote (one), because when i tried changed the [0][(Here supposed to be "1")], the text automatically changed to linked image"
Issue: **"When i tried the code
else if (textBoxQuantityContainer[0][0].Text == "1")
{
textBoxTotalContainer[0][0].Text = textBoxSubTotalContainer[0][0].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][0].Text;
}
the textbox for alltotalcontainer is on (Total on Rp, the textbox is on after words) in the image shown above, the textboxes for subtotal is on (Sub Total on Rp), the textboxes for totalcontainer is on (Total on Rp, the textboxes are on below words), the textboxes for quantitycontainer is on (Quantity). In code above, shown that textbox 1 on textboxtotalcontainer are same with the textbox 1 on subtotalcontainer, and alltotalcontainer is same with totalcontainer.**
But, below code it not working, and the screen stucked on there (the mouse dissappear and i cant do anything, unless i press SHIFT + F5 on Visual Studio):
else if (textBoxQuantityContainer[0][1].Text == "1")
{
textBoxTotalContainer[0][1].Text = textBoxSubTotalContainer[0][1].Text;
textBoxAllTotalContainer.Text = textBoxTotalContainer[0][1].Text;
}
Thanks
You get that error when you try to access an element in a collection that doesn't exist.
For example, if you have a list of strings...
List<string> myList = new List {"one", "two", "three"};
...and try to access the fourth element with myList[3], you'll get that error.
Either textBoxAllTotalContainer[0][2] doesn't exist, or textBoxTotalContainer[0][2]. Can't tell from the error in your picture. Place a breakpoint on that line and check both objects.
Looks like your stop condition is wrong.
you have the following code for initializing textBoxAllTotalContainer:
//****TextBox for Total All****
for (int y = 0; y <= 1; y++)
{
textBoxAllTotalContainer.Add(new List<TextBox>());
textBoxAllTotalContainer[0].Add(new TextBox());
textBoxAllTotalContainer[0][y].Size = new Size(175, 50);
textBoxAllTotalContainer[0][y].Location = new Point(1150, 575);
textBoxAllTotalContainer[0][y].TextChanged += new System.EventHandler(this.textBox_TextChanged);
Controls.Add(textBoxAllTotalContainer[0][y]);
}
Note that the loop is itterating only twice.
Therefore textBoxAllTotalContainer[0][0] and textBoxAllTotalContainer[0][1] are created.
but when you try to access textBoxAllTotalContainer[0][2] you hit the exception because the location is really out of the list's range as the exception specifies.
Related
I have a WPF App that allows the user to choose one to many spreadsheets and performs a process to clean the data and write out a pipe delimited files. I am trying to use a Background Worker in order to display a progress bar. The problem I am having is that I have the backgroundworker_DoWork routine to perform the read the excel file, clean the data and write out the data. For each spreadsheet the user is allowed to specify the range for the data or to let Excel decided the range. I call a dialog for this input. I get the error "The calling thread must be STA, because many UI components require this." I have been trying to find a fix for this but everything I try doesn't work.
Here is my code. I have put comments where the offending code is and what I have tried so far.
private void ProcessFiles()
{
int intNumFiles = 0;
string strFileType = "";
int intPos = 0;
string strMsg = "";
intNumFiles = strExFileNames.Length;
foreach (string strInputFile in strExFileNames)
{
intPos = strInputFile.LastIndexOf(".");
strFileType = strInputFile.Substring(intPos + 1);
if(!blnEXTextFileFound)
{
strExcelInputFile = strInputFile;
if (blnExParamCancel || blnMWCancel)
{
strMsg = "Processing has been cancelled.";
System.Windows.MessageBox.Show(strMsg);
break;
}
prgExcelProgress.Visibility = Visibility.Visible;
txtExcelPercent.Visibility = Visibility.Visible;
EnterExcelStateRunning();
try
{
bgwExcelRunner.RunWorkerAsync(strInputFile);
}
catch (Exception ex)
{
System.Windows.MessageBox.Show("Trying to run the Excel/Text file clean process resulted in this error: " + ex.Message, " Error");
prgExcelProgress.Foreground = new SolidColorBrush(Colors.DarkRed);
prgExcelProgress.Value = 100;
}
//ReadWriteExcelData(strInputFile);
}
else
{
if (blnEXTextFileFound)
{
ProcessDelimitedFile(strInputFile);
}
else
{
strMsg = "File type " + strFileType + " is not supported.";
strMsg += " Please contact support.";
System.Windows.MessageBox.Show(strMsg);
}
}
}
prgExcelProgress.Value = 100;
//prgIndicator.Width = 400;
//lblPrctPrgrs.Content = "100%";
//grdProgressIndicator.InvalidateVisual();
//System.Windows.Forms.Application.DoEvents();
//Thread.Sleep(2000);
//txtIndicator.Text = "All files have been processed and created in " + strExOutputPath + ".";
blnDoForAll = false;
}
private void bgwExcelRunner_DoWork(object sender, DoWorkEventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range, colrange, rowrange;
string strCellData, strMsg;
string strDataRow = "";
long lngNumRows, lngNumCols = 0;
long intModNumber, lngProgressPct = 0;
double dblProgress = 0;
double dblProgressPct = 0;
string strOutputFileName = "";
int intPos, intProgress = 0;
string strSubFileName = "";
string strFullOutputFileName = "";
string strOutName = "";
long lngColCnt;
string[] strWSNames = new string[0];
Type typCellType;
bool blnMultiWS = false;
string strNumberFormat;
string strFileName = (string)e.Argument;
//string strFileName = (string)((object[])e.Argument)[0];
intPos = strFileName.IndexOf(".");
strSubFileName = strFileName.Substring(0, intPos);
strOutputFileName = strFileName.Substring(strFileName.LastIndexOf("\\") + 1);
strOutName = strOutputFileName.Substring(0, strOutputFileName.IndexOf("."));
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(strFileName, 0, true, 5, "", "", true,
Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
Excel.Sheets excelSheets = xlWorkBook.Worksheets;
if (excelSheets.Count > 1)
{
blnMultiWS = CheckMultipleWorksheets(excelSheets);
if (!blnMultiWS)
{
Array.Clear(strChoosenNames, 0, strChoosenNames.Length);
Array.Resize(ref strChoosenNames, 1);
strChoosenNames[0] = strOutName;
}
}
else
{
Array.Resize(ref strChoosenNames, 1);
strChoosenNames[0] = strOutName;
}
if (blnMWCancel)
{
strMsg = "Processing has been cancelled.";
System.Windows.MessageBox.Show(strMsg);
goto ReadWriteExcelDataExit;
}
foreach (string strCurrWSName in strChoosenNames)
{
//grdProgressIndicator.Visibility = Visibility.Visible;
//txtIndicator.Text = "File: " + strCurrWSName;
//prgIndicator.Width = 0;
//lblPrctPrgrs.Content = "0%";
//System.Windows.Forms.Application.DoEvents();
//txtIndicator.Text = " Processing File: " + strCurrWSName + ". Please wait...";
strFullOutputFileName = strExOutputPath + "\\" + strCurrWSName + "_duc.txt";
//if (strChoosenNames.Length > 1)
//{
// xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[strCurrWSName];
//}
//else
//{
// xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//}
try
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets[strCurrWSName];
}
catch (Exception exQuery)
{
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
}
if (!blnDoForAll)
{
// I ALSO TRIED TO USE A THREAD. THIS SEEMS TO WORK EXCEPT THAT IT PROCESSING DOESN'T RUN IN THE FOREGROUND SO IT FALLS TO THE CODE AFTER BEFORE THE DIALOG IS DISPLAYED
//Thread thread = new Thread(() =>
//{
// ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
// ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
// ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
// ercWin.ShowDialog();
// blnExParamCancel = ercWin.blnExCancel;
// strExcelStartCol = ercWin.strStartCol;
// strExcelEndCol = ercWin.strEndCol;
// lngExcelStartRow = ercWin.lngStartRow;
// lngExcelEndRow = ercWin.lngEndRow;
// blnLetExcelDecide = ercWin.blnExcelDecide;
// blnDoForAll = ercWin.blnDoForAll;
//});
//thread.SetApartmentState(ApartmentState.STA);
//thread.IsBackground = false;
//thread.Start();
// THIS IS ONE ATTEMPT TO USE A DISPATCHER, STILL GET THE STA ERROR
//ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
//ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
//ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
//ercWin.Dispatcher.BeginInvoke
// (
// System.Windows.Threading.DispatcherPriority.Normal,
// (Action)(() =>
// {
// ercWin.ShowDialog();
// blnExParamCancel = ercWin.blnExCancel;
// }
// )
// );
// THIS IS WHERE THE ERROR OCCURS
ExcelRowColInfo ercWin = new ExcelRowColInfo(xlWorkSheet.Name);
ercWin.Left = System.Windows.Application.Current.MainWindow.Left + 15;
ercWin.Top = System.Windows.Application.Current.MainWindow.Top + 15;
ercWin.ShowDialog();
blnExParamCancel = ercWin.blnExCancel;
if (blnExParamCancel)
{
prgExcelProgress.Foreground = new SolidColorBrush(Colors.LightPink);
Dispatcher.BeginInvoke((Action)delegate
{
prgExcelProgress.Value = 100;
txtExcelPercent.Text = "Process has been cancelled";
});
blnExParamCancel = false;
goto ReadWriteExcelDataExit;
}
strExcelStartCol = ercWin.strStartCol;
strExcelEndCol = ercWin.strEndCol;
lngExcelStartRow = ercWin.lngStartRow;
lngExcelEndRow = ercWin.lngEndRow;
blnLetExcelDecide = ercWin.blnExcelDecide;
blnDoForAll = ercWin.blnDoForAll;
if (blnLetExcelDecide)
{
range = xlWorkSheet.UsedRange;
}
else
{
Excel.Range c1 = xlWorkSheet.Cells[lngExcelStartRow, strExcelStartCol];
Excel.Range c2 = xlWorkSheet.Cells[lngExcelEndRow, strExcelEndCol];
range = (Excel.Range)xlWorkSheet.get_Range(c1, c2);
}
colrange = range.Columns;
lngNumCols = colrange.Count;
rowrange = range.Rows;
lngNumRows = rowrange.Count;
if (lngNumRows < 10)
{
intModNumber = lngNumRows;
}
else
{
intModNumber = lngNumRows / 10;
}
if (System.IO.File.Exists(#strFullOutputFileName))
{
System.IO.File.Delete(#strFullOutputFileName);
}
object[,] values = (object[,])range.Value;
long NumRow = 1;
using (StreamWriter file = new StreamWriter(#strFullOutputFileName, true, Encoding.GetEncoding("iso-8859-1")))
{
while (NumRow <= values.GetLength(0))
{
strDataRow = "";
for (lngColCnt = 1; lngColCnt <= lngNumCols; lngColCnt++)
{
if (values[NumRow, lngColCnt] == null)
{
typCellType = typeof(System.String);
}
else
{
typCellType = values[NumRow, lngColCnt].GetType();
}
strCellData = Convert.ToString(values[NumRow, lngColCnt]);
if (typCellType == typeof(System.DateTime))
{
strCellData = strCellData.Substring(0, strCellData.IndexOf(" "));
}
else
{
if (typCellType == typeof(System.Decimal))
{
if (Convert.ToDecimal(values[NumRow, lngColCnt]) == 0)
{
strCellData = Convert.ToString(0);
}
else
{
strCellData = Convert.ToString(values[NumRow, lngColCnt]);
}
}
else
{
if (typCellType != typeof(System.String))
{
strNumberFormat = range[NumRow, lngColCnt].NumberFormat.ToString();
if (strNumberFormat != "General" && strNumberFormat != "Text" && strNumberFormat != "#")
{
if (typCellType == typeof(System.Double))
{
if (strNumberFormat.IndexOf("[Red]") > 0)
{
strCellData = Convert.ToString(range[NumRow, lngColCnt].Value2);
}
else
{
double dblCellValue = double.Parse(strCellData);
strCellData = dblCellValue.ToString(strNumberFormat);
}
}
}
}
}
}
if (strCellData == null)
{
strCellData = string.Empty;
}
else
{
strCellData = strCellData.Replace("\r\n", " ").Replace("\n", " ").Replace("\r", " ");
}
if (lngColCnt == lngNumCols)
{
strDataRow += strCellData;
}
else
{
strDataRow += strCellData + "|";
}
}
file.WriteLine(strDataRow);
if (NumRow % intModNumber == 0)
{
lngProgressPct = (NumRow / lngNumRows);
bgwExcelRunner.ReportProgress((int)lngProgressPct);
}
NumRow++;
}
}
releaseObject(xlWorkSheet);
}
xlWorkBook.Close(false, null, null);
ReadWriteExcelDataExit:
blnMWCancel = false;
xlApp.Quit();
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
Here is the entry point for the ExcelRowColInfo window.
public ExcelRowColInfo(string strWSName)
{
InitializeComponent();
strCurrWSName = string.Copy(strWSName);
InitializeExcelParams();
}
I tried to put [STAThread] above this but get the error "Attributre 'STAThread' is not valid on this declaration type. It is only valid on 'Method' declaration.
How do I do this correctly?
I am trying to implement load and go sic assembler, I have used 3 gridviews one stores the read pgm , menoic values and other an empty gridview which would act as symbole table I am having trouble while trying to enter new value gridview that should hold symbole and its address,here is my code.
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
static System.Data.OleDb.OleDbConnection con1 = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=D:/ASSEMBLER.mdb");
string start_address;
int k = 0;
string value;
int ma;
int nxt_add = 0;
string opcode;
public Form2()
{
InitializeComponent();
grid1();
grid2();
grid3();
}
private void grid1()
{
// var ss = new List<string> { "BYTE", "RESW", "RESB", "WORD" };
try
{
// InitializeComponent();
DataSet ds = new DataSet();
System.Data.OleDb.OleDbDataAdapter adapReport = new System.Data.OleDb.OleDbDataAdapter("select Adress as [address], opcode as [Symbol],operand as [opco],op as [operand],ooo as[obj] from read_pgm" + "'", con1);
adapReport.Fill(ds, "read_pgm");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "read_pgm";
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.Rows[i].Cells[1].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.Rows[i].Cells[2].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.Rows[i].Cells[3].Style.Font = new Font("Arial", 9, FontStyle.Bold);
}
Int16 b = Convert.ToInt16(dataGridView1.Rows[1].Cells[0].Value);
//start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
// MessageBox.Show(add + " in second form");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con1.Close();
}
}
private void grid2()
{
con1.Open();
try
{
//InitializeComponent();
DataSet ds1 = new DataSet();
System.Data.OleDb.OleDbDataAdapter adapReport = new System.Data.OleDb.OleDbDataAdapter("select SYMBOLE as [Symbol],ADDRESS as [ADDRESS] from SYMBOL_TABLE" + "'", con1);
adapReport.Fill(ds1, "SYMBOL_TABLE");
dataGridView2.AutoGenerateColumns = true;
dataGridView2.DataSource = ds1;
dataGridView2.DataMember = "SYMBOL_TABLE";
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
{
dataGridView2.Rows[i].Cells[0].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView2.Rows[i].Cells[1].Style.Font = new Font("Arial", 9, FontStyle.Bold);
}
//Int16 b = Convert.ToInt16(dataGridView1.Rows[1].Cells[0].Value);
//start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
// MessageBox.Show(add + " in second form");
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void grid3()
{
try
{
con1.Open();
// InitializeComponent();
DataSet ds2 = new DataSet();
System.Data.OleDb.OleDbDataAdapter adapReport = new System.Data.OleDb.OleDbDataAdapter("select opcode as [opcode],val as [value] from Mnemoni" + "'", con1);
adapReport.Fill(ds2, "Mnemoni");
dataGridView3.AutoGenerateColumns = true;
dataGridView3.DataSource = ds2;
dataGridView3.DataMember = "Mnemoni";
foreach (DataGridViewColumn col in dataGridView3.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
for (int i = 0; i < dataGridView3.Rows.Count - 1; i++)
{
dataGridView3.Rows[i].Cells[0].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView3.Rows[i].Cells[1].Style.Font = new Font("Arial", 9, FontStyle.Bold);
}
//Int16 b = Convert.ToInt16(dataGridView1.Rows[1].Cells[0].Value);
//start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
// MessageBox.Show(add + " in second form");
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form2_Load(object sender, EventArgs e)
{
cal(dataGridView1, dataGridView2, dataGridView3);
}
private void add()
{
try
{
con1.Open();
System.Data.OleDb.OleDbCommand top = new System.Data.OleDb.OleDbCommand(
"INSERT INTO SYMBOL_TABLE (" +
"SYMBOLE,ADDRESS" +
") VALUES (?,?)", con1);
top.Parameters.AddWithValue("?", opcode);
top.Parameters.AddWithValue("?", "xxxx");
top.ExecuteNonQuery();
con1.Close();
grid2();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void cal(DataGridView dataGridView1, DataGridView dataGridView2, DataGridView dataGridView3)
{
start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
MessageBox.Show("this is start adder" + start_address);
for (int i = 1; i < dataGridView1.Rows.Count; i++)
{
opcode = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
string operand = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
string op = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
MessageBox.Show(opcode);
string cv = dataGridView1.Rows[i].Cells[0].Value.ToString();
MessageBox.Show(cv);
// int nxt_add =Convert.ToInt16(cv);
nxt_add = nxt_add + 3;
string address = nxt_add.ToString("X");
dataGridView1.Rows[i + 1].Cells[0].Value = address;
// MessageBox.Show(operand);
//MessageBox.Show(op);
if (opcode != null && opcode != "")
{
MessageBox.Show("inside opcode loop");
for (int j = 0; j < dataGridView2.Rows.Count; j++)
{
//MessageBox.Show(dataGridView2.Rows[j].Cells[0].Value.ToString());
try
{
if (dataGridView2.Rows[j].Cells[0].Value.ToString() == opcode)
{
ma = j;
string m = dataGridView1.Rows[j].Cells[0].Value.ToString();
MessageBox.Show("value of m" + m);
dataGridView2.Rows[j].Cells[1].Value = m;
MessageBox.Show("if condition satisified block of opcode and it is exiting now ");
break;
}
}
catch (NullReferenceException e)
{
MessageBox.Show("opcode value is " + opcode);
int a = dataGridView2.NewRowIndex;
dataGridView2.Rows[a].Cells[0].Value = opcode;
dataGridView2.Rows[a].Cells[1].Value = "xxxx";
// ma = k;
// k++;
MessageBox.Show("exiting catch block of opcode");
break;
}
}
}
for (int y = 0; y < dataGridView2.Rows.Count; y++)
{
MessageBox.Show("content of symbole table");
MessageBox.Show(dataGridView2.Rows[y].Cells[0].Value.ToString());
MessageBox.Show(dataGridView2.Rows[y].Cells[1].Value.ToString());
}
if (operand != null)
{
MessageBox.Show("inside the operan loop");
for (int kj = 0; kj < dataGridView3.Rows.Count; kj++)
{
try
{
if (dataGridView3.Rows[kj].Cells[0].Value.ToString() == operand)
{
value = dataGridView3.Rows[kj].Cells[1].Value.ToString();
MessageBox.Show(value);
break;
}
else
{
// MessageBox.Show("invalid operand");
continue;
}
}
catch (Exception e)
{
MessageBox.Show("inside the catch block of operand loop ");
// MessageBox.Show(e.Message+e.InnerException);
}
}
}
if (op != null)
{
MessageBox.Show("in the op loop");
if (op == "")
{
MessageBox.Show("op is empty space ****");
}
int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
if (op.Contains(Convert.ToString(num)))
{
}
int f = dataGridView2.CurrentCellAddress.X;
for (int j = 0; j < dataGridView2.Rows.Count; j++)
{
//MessageBox.Show(dataGridView2.Rows[j].Cells[0].Value.ToString());
try
{
if (dataGridView2.Rows[j].Cells[0].Value.ToString() == opcode)
{
ma = j;
string m = dataGridView1.Rows[j].Cells[0].Value.ToString();
MessageBox.Show("value of m" + m);
dataGridView2.Rows[j].Cells[1].Value = m;
MessageBox.Show("if condition satisified block of opcode and it is exiting now ");
break;
}
}
catch (NullReferenceException e)
{
MessageBox.Show("opcode value is " + opcode);
int a = dataGridView2.NewRowIndex;
dataGridView2.Rows[a].Cells[0].Value = opcode;
dataGridView2.Rows[a].Cells[1].Value = "xxxx";
// ma = k;
// k++;
MessageBox.Show("exiting catch block of opcode");
break;
}
MessageBox.Show("op value is " + op);
try
{
int b = dataGridView2.NewRowIndex;
dataGridView2.Rows[b].Cells[0].Value = op;
dataGridView2.Rows[b].Cells[1].Value = "xxxx";
}
catch (Exception v)
{
MessageBox.Show(v.Message);
}
// dataGridView2.BeginEdit(true);
// dataGridView2.EndEdit();
MessageBox.Show("exiting op loop");
}
MessageBox.Show("value of i is " + i);
for (int o = 0; o < dataGridView2.Rows.Count; o++)
{
MessageBox.Show(dataGridView2.Rows[o].Cells[0].Value.ToString());
MessageBox.Show(dataGridView2.Rows[o].Cells[1].Value.ToString());
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I have found solution for my question with few modification I have completed simple sic load and go assembler. my code as follows `
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
string opcode;
string labelz;
string operand;
string m;
string fg;
string d;
int a = 0;
string value;
static System.Data.OleDb.OleDbConnection con1 = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=D:/ASSEMBLER.mdb");
public Form2()
{
InitializeComponent();
grid1();
grid2();
grid3();
}
private void grid1()
{
try
{
DataSet ds = new DataSet();
System.Data.OleDb.OleDbDataAdapter adapReport = new System.Data.OleDb.OleDbDataAdapter("select Adress as [address], opcode as [Symbol],operand as [opco],op as [operand],ooo as[obj] from read_pgm" + "'", con1);
adapReport.Fill(ds, "read_pgm");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "read_pgm";
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.Rows[i].Cells[1].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.Rows[i].Cells[2].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView1.Rows[i].Cells[3].Style.Font = new Font("Arial", 9, FontStyle.Bold);
}
Int16 b = Convert.ToInt16(dataGridView1.Rows[1].Cells[0].Value);
//start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
// MessageBox.Show(add + " in second form");
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void grid2()
{
con1.Open();
try
{
DataSet ds1 = new DataSet();
System.Data.OleDb.OleDbDataAdapter adapReport = new System.Data.OleDb.OleDbDataAdapter("select SYMBOLE as [Symbol],ADDRESS as [ADDRESS] from SYMBOL_TABLE" + "'", con1);
adapReport.Fill(ds1, "SYMBOL_TABLE");
dataGridView2.AutoGenerateColumns = true;
dataGridView2.DataSource = ds1;
dataGridView2.DataMember = "SYMBOL_TABLE";
foreach (DataGridViewColumn col in dataGridView2.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)
{
dataGridView2.Rows[i].Cells[0].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView2.Rows[i].Cells[1].Style.Font = new Font("Arial", 9, FontStyle.Bold);
}
//Int16 b = Convert.ToInt16(dataGridView1.Rows[1].Cells[0].Value);
//start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
// MessageBox.Show(add + " in second form");
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
//con1.Close();
}
private void grid3()
{
con1.Open();
try
{
DataSet ds2 = new DataSet();
System.Data.OleDb.OleDbDataAdapter adapReport = new System.Data.OleDb.OleDbDataAdapter("select opcode as [opcode],val as [value] from Mnemoni" + "'", con1);
adapReport.Fill(ds2, "Mnemoni");
dataGridView3.AutoGenerateColumns = true;
dataGridView3.DataSource = ds2;
dataGridView3.DataMember = "Mnemoni";
foreach (DataGridViewColumn col in dataGridView3.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
for (int i = 0; i < dataGridView3.Rows.Count - 1; i++)
{
dataGridView3.Rows[i].Cells[0].Style.Font = new Font("Arial", 9, FontStyle.Bold);
dataGridView3.Rows[i].Cells[1].Style.Font = new Font("Arial", 9, FontStyle.Bold);
}
//Int16 b = Convert.ToInt16(dataGridView1.Rows[1].Cells[0].Value);
//start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
// MessageBox.Show(add + " in second form");
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}##
Heading
#
private void cal(DataGridView dataGridView1, DataGridView dataGridView2, DataGridView dataGridView3)
{
string start_address = Convert.ToString(dataGridView1.Rows[1].Cells[0].Value);
/// MessageBox.Show("this is start adder" + start_address);
for (int i = 1; i < dataGridView1.Rows.Count - 2; i++)
{
labelz = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
opcode = Convert.ToString(dataGridView1.Rows[i].Cells[2].Value);
operand = Convert.ToString(dataGridView1.Rows[i].Cells[3].Value);
string objcod = Convert.ToString(dataGridView1.Rows[i].Cells[4].Value);
a = a + Convert.ToInt16(3);
// start_address = Convert.ToString(a);
string s = a.ToString("X");
string bv = a.ToString();
if (dataGridView1.Rows[i].Cells[2].Value.ToString() != "END")
{
if (bv.Length == 2)
{
string tr = start_address.Remove(1, 2);
dataGridView1.Rows[i + 1].Cells[0].Value = tr + s;
}
else if (bv.Length < 2)
{
string tr = start_address.Remove(2, 1);
dataGridView1.Rows[i + 1].Cells[0].Value = tr + s;
}
}
d = dataGridView1.Rows[i].Cells[0].Value.ToString();
if (labelz != null && labelz != "")
{
MessageBox.Show("label is" + labelz + " value is" + d);
im(labelz, d);
grid2();
}
if (opcode != null)
{
for (int kj = 0; kj < dataGridView3.Rows.Count; kj++)
{
try
{
if (dataGridView3.Rows[kj].Cells[0].Value.ToString() == opcode)
{
dataGridView1.Rows[i].Cells[4].Value = dataGridView3.Rows[kj].Cells[1].Value.ToString();
value = dataGridView3.Rows[kj].Cells[1].Value.ToString();
break;
}
}
catch (Exception e)
{
string qw = dataGridView1.Rows[i].Cells[3].Value.ToString();
if (qw.Length == 4)
{
value = "00" + qw;
dataGridView1.Rows[i].Cells[4].Value = value;
}
if (qw.Length == 1)
{
value = "00000" + qw;
dataGridView1.Rows[i].Cells[4].Value = value;
}
if (qw.Length == 2)
{
value = "0000" + qw;
dataGridView1.Rows[i].Cells[4].Value = value;
}
if (qw.Length == 3)
{
value = "000" + qw;
dataGridView1.Rows[i].Cells[4].Value = value;
}
}
}
if (operand != ""&& opcode != "WORD" | opcode != "RESW")
{
try
{
for (int jm = 0; jm < dataGridView1.Rows.Count - 1; jm++)
{
//break;
if (dataGridView2.Rows[jm].Cells[0].Value.ToString() == operand)
{
for (int hj = 0; hj < dataGridView1.Rows.Count; hj++)
{
if (dataGridView1.Rows[hj].Cells[1].Value.ToString() == operand)
{
m = dataGridView1.Rows[hj].Cells[0].Value.ToString();
MessageBox.Show("symbole" + operand + " is already in symbol table" + "with address" + m);
cv(operand,m);
grid2();
break;
}
/* else
{
cv(operand,"XXXX");
grid2();
}*/
}
}
}
}
catch (NullReferenceException e)
{
MessageBox.Show("symbol" + operand + "is not present in symbol table & entered with value" + "xxxx");
cv(operand, "XXXX");
grid2();
//break;
}
}
if (operand == "")
{
dataGridView1.Rows[i].Cells[4].Value = value + "0000";
}
}
MessageBox.Show("object code is" + dataGridView1.Rows[i].Cells[4].Value.ToString());
if (dataGridView1.Rows[i].Cells[4].Value.ToString() == "")
{
for (int jh = 0; jh < dataGridView2.Rows.Count; jh++)
{
try
{
if (dataGridView2.Rows[jh].Cells[0].Value.ToString() == operand)
{
fg = dataGridView2.Rows[jh].Cells[1].Value.ToString();
dataGridView1.Rows[i].Cells[4].Value = value + fg;
MessageBox.Show(operand);
break;
}
}
catch (NullReferenceException v)
{
break;
}
}
}
for (int mi = 1; mi < dataGridView1.Rows.Count - 2; mi++)
{
if (dataGridView1.Rows[mi].Cells[0].Value.ToString().Length == 3)
{
string sd = dataGridView1.Rows[mi].Cells[0].Value.ToString();
sd = sd.Insert(1, "0");
dataGridView1.Rows[mi].Cells[0].Value = sd;
}
try
{
string kj = dataGridView1.Rows[mi].Cells[4].Value.ToString();
// MessageBox.Show("kj length is" + kj.Length);
if (kj.Length < 6)
{
for (int re = 0; re < dataGridView2.Rows.Count; re++)
{
if (dataGridView2.Rows[re].Cells[0].Value.ToString() == dataGridView1.Rows[mi].Cells[3].Value.ToString())
{
string vv = dataGridView2.Rows[re].Cells[1].Value.ToString();
dataGridView1.Rows[mi].Cells[4].Value = kj + vv;
}
}
}
}
catch (NullReferenceException v)
{
}
}
}
}
private static void im(string lab, string d)
{
System.Data.OleDb.OleDbConnection con1 = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=D:/ASSEMBLER.mdb");
try
{
con1.Open();
System.Data.OleDb.OleDbCommand top = new System.Data.OleDb.OleDbCommand(
"INSERT INTO SYMBOL_TABLE (" +
"SYMBOLE,ADDRESS" +
") VALUES (?,?)", con1);
top.Parameters.AddWithValue("?", lab);
top.Parameters.AddWithValue("?", d);
// top.Parameters.AddWithValue("?", mcs[2]);
top.ExecuteNonQuery();
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public static void cv(string a, string b)
{
try
{
con1.Open();
System.Data.OleDb.OleDbCommand top1 = new System.Data.OleDb.OleDbCommand("UPDATE SYMBOL_TABLE SET[ADDRESS] = ? where SYMBOLE = ?", con1);
top1.Parameters.AddWithValue("?", a);
top1.Parameters.AddWithValue("?", b);
top1.ExecuteNonQuery();
con1.Close();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private void Form2_Load(object sender, EventArgs e)
{
cal(dataGridView1, dataGridView2, dataGridView3);
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
`
I'm trying to get a report from a custom query accessing to a Microsoft Access Database filling a Dataset and then a CrystalReportViwer but I just got an empty report with the column names.
This is my connection:
public String ConectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data";
public OleDbConnection miconexion;
public Int32 retorna = 0;
public Int32 conectar(String location){
try
{
ConectionString += #" Source="+location;
miconexion = new OleDbConnection(ConectionString);
//Open Database Conexion
miconexion.Open();
retorna = 1;
}
catch (OleDbException ex){
retorna = 0;
MessageBox.Show("Database Error: "+ex.ToString());
}
return retorna;
}
public void desconectar() {
if(miconexion.State == ConnectionState.Open){
miconexion.Close();
}
}
Method that process the sql //---------------------------------
//txt_CustomConsult is the textbox that contains the custom query.
public String ExecuteSQl()
{
string sql = null;
string inSql = null;
string firstPart = null;
string LastPart = null;
int SelectStart = 0;
int fromStart = 0;
string[] fields = null;
string[] sep = { "," };
int i = 0;
TextObject MyText;
inSql = txt_CustomConsult.Text;
inSql = inSql.ToUpper();
SelectStart = inSql.IndexOf("SELECT");
fromStart = inSql.IndexOf("FROM");
SelectStart = SelectStart + 6;
firstPart = inSql.Substring(SelectStart, (fromStart - SelectStart));
LastPart = inSql.Substring(fromStart, inSql.Length - fromStart);
fields = firstPart.Split(',');
firstPart = "";
for (i = 0; i <= fields.Length - 1; i++) {
if (i > 0)
{
firstPart = firstPart + ", " + fields[i].ToString() + " AS COLUMN" + (i + 1);
firstPart.Trim();
MyText = (TextObject)ObjRep.ReportDefinition.ReportObjects[i + 1];
MyText.Text = fields[i].ToString();
}
else {
firstPart = firstPart + fields[i].ToString() + " AS COLUMN"+(i+1);
firstPart.Trim();
MyText = (TextObject)ObjRep.ReportDefinition.ReportObjects[i + 1];
MyText.Text = fields[i].ToString();
}
}
sql = "SELECT "+firstPart+" "+LastPart;
return sql;
}
// ---------------------------------------------------
Method that exceute report. lstbx_Tablas is the ListBox that contains all tables,
I got all the tables but report doesn't work.
public void DynamicRep() {
try {
//Windows Form where the rpt is located
ReporteResult mirepres = new ReporteResult();
//Connection
conexion miconect = new conexion();
miconect.conectar(Environment.GetEnvironmentVariable("dbUbicacion"));
String sql = ExecuteSQl();
OleDbDataAdapter dscm = new OleDbDataAdapter(sql,miconect.miconexion);
MisConsultas Dataset1 = new MisConsultas();
dscm.Fill(Dataset1,lstbx_Tablas.SelectedItem.ToString());
ObjRep.SetDataSource(Dataset1.Tables[0]);
mirepres.crv_Reporte.ReportSource = ObjRep;
mirepres.crv_Reporte.Refresh();
mirepres.Show();
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
}
Through a series of loops and Database calls (Select statements only) saved as datatables I am generating a .txt file with the values. It runs fine for a little while (19 rows...19 full loop cycles) then I get a runtime exception being thrown by connection.Open()
I have the entire loop inside a try catch block in order to catch the exception and produce the message then 2 blank lines then the stack trace.
I have tried to read this and figure out what to do but I am a bit of a Novice when it comes to DB connections. I have looked elsewhere but do not seem to find a question that quite fits my situation.
FYI: C# 4.0 Windows Form Application, Access DB
I am hoping to find some suggestions on where to begin looking. I am positive that my connection is closed when this error is thrown due to the validation i implemented as shown here:
internal IDbConnection GetConnection()
{
try
{
var connection = _assemblyProvider.Factory.CreateConnection();
connection.ConnectionString = _connectionString;
_connectionState = connection.State.ToString();
if (_connectionState == "Open")
GetConnection();
else
{
connection.Open();
}
return connection;
}
catch (Exception exept)
{
throw new Exception(exept.ToString() + "\n\n" + exept.StackTrace.ToString());
}
}
This method is being called from here:
public DataTable ExecuteDataTable(string commandText, string tableName, DbParameterCollection paramCollection, CommandType commandType)
{
DataTable dtReturn;
IDbConnection connection = null;
try
{
connection = _connectionManager.GetConnection();
dtReturn = _dbAdapterManager.GetDataTable(commandText, paramCollection, connection, tableName, commandType);
}
finally
{
if (connection != null)
{
connection.Close();
connection.Dispose();
}
}
return dtReturn;
}
public DataTable ExecuteDataTable(string commandText, string tableName, CommandType commandType)
{
return ExecuteDataTable(commandText, tableName, new DbParameterCollection(), commandType);
}
public DataTable ExecuteDataTable(string commandText)
{
return ExecuteDataTable(commandText, string.Empty, CommandType.Text);
}
and
//read from DB using a SQL statement and return a DataTable
internal static DataTable readDB(string SQL)
{
var dbHelper = new DbHelper();
using (IDbConnection connection = dbHelper.GetConnObject())
{
return dbHelper.ExecuteDataTable(SQL);
}
}
Here is the loop (its kinda long and could probably be done better but I just want to find why its breaking after its worked several times)
The exception is thrown from the line that Reads:
DataTable iRecNum2ClaimRecNumFromClaim = dbConnect.readDB(SQLString);
inside this:
SQLString = "SELECT * FROM Claim WHERE ClaimStatus <> 1";
DataTable allRecsFromClaimNotStatus1 = dbConnect.readDB(SQLString);
if (allRecsFromClaimNotStatus1.Rows.Count == 0)
return;
else
{
string path = txtExtractFileLocation.Text;
if (txtExtractFileLocation.Text.Substring(txtExtractFileLocation.Text.Length - 2) == "\\\\")
{
path = path.Substring(0, path.Length - 1);
}
if (path.Substring(path.Length - 1) == "\\")
path += "DI_Extract.txt";
else
path += #"\DI_Extract.txt";
using (StreamWriter sw = new StreamWriter(#path))
{
for (int i = 0; i < allRecsFromClaimNotStatus1.Rows.Count; i++)
{
rNum = allRecsFromClaimNotStatus1.Rows[i][2].ToString().Trim();//Claim.InsuredRecNum
SQLString = "SELECT * FROM Insured WHERE RecNum = " + rNum;
DataTable allInsuredByRecNum = dbConnect.readDB(SQLString);
lossDate = allRecsFromClaimNotStatus1.Rows[i][11].ToString().Trim();//Claim.LossDate
lossDate = (Convert.ToDateTime(lossDate)).Date.ToString("MM/dd/yyyy");
reportedDate = allRecsFromClaimNotStatus1.Rows[i][9].ToString().Trim();//Claim.ReportedDate
reportedDate = (Convert.ToDateTime(reportedDate)).Date.ToString("MM/dd/yyyy");
claim = allRecsFromClaimNotStatus1.Rows[i][0].ToString().Trim();//Claim.ClaimNumber
if (chkIncludePaymentsForCurrentMonth.Checked == true)
{
direct = allRecsFromClaimNotStatus1.Rows[i][4].ToString().Trim();//Claim.DirectReserve
WP = allRecsFromClaimNotStatus1.Rows[i][5].ToString().Trim();//Claim.WPReserve
ceded = allRecsFromClaimNotStatus1.Rows[i][6].ToString().Trim();//Claim.CededReserve
}
else
{
direct = allRecsFromClaimNotStatus1.Rows[i][29].ToString().Trim();//Claim.MonthEndDirect
WP = allRecsFromClaimNotStatus1.Rows[i][30].ToString().Trim();//Claim.MonthEndWP
ceded = allRecsFromClaimNotStatus1.Rows[i][31].ToString().Trim();//Claim.MonthEndCeded
}
ced = Convert.ToDecimal(ceded);
wav = Convert.ToDecimal(WP);
ceded = ced.ToString("#.##");
WP = wav.ToString("#.##");
if (ceded == "")
ceded = "0";
if (WP == "")
WP = "0";
if ((allRecsFromClaimNotStatus1.Rows[i][10].ToString().Trim() != null) &&
(allRecsFromClaimNotStatus1.Rows[i][10].ToString().Trim() != ""))//Claim.WaiverDate
{
onWaiver = "YES";
}
else
{
onWaiver = "NO";
}
reinsPreNotice = "NO";
reinsCeded = "NO";
switch (allRecsFromClaimNotStatus1.Rows[i][7].ToString().Trim())//Claim.CededPre
{
case "1":
{
reinsPreNotice = "YES";
break;
}
case "2":
{
reinsCeded = "YES";
break;
}
}//end switch
state = allRecsFromClaimNotStatus1.Rows[i][8].ToString().Trim();//Claim.LossState
lName = allInsuredByRecNum.Rows[0][1].ToString().Trim();//Insured.LastName
fName = allInsuredByRecNum.Rows[0][0].ToString().Trim();//Insured.FirstName
mi = allInsuredByRecNum.Rows[0][2].ToString().Trim();//Insured.MI
policy = allInsuredByRecNum.Rows[0][43].ToString().Trim();//Insured.PolicyNumber
DOB = allInsuredByRecNum.Rows[0][10].ToString().Trim();//Insured.DOB
DOB = (Convert.ToDateTime(DOB)).Date.ToString("MM/dd/yyyy");
age = allInsuredByRecNum.Rows[0][11].ToString().Trim();//Insured.TrueAge
issueAge = calculateAge(Convert.ToDateTime(allInsuredByRecNum.Rows[0][10].ToString().Trim()), //Insured.DOB
Convert.ToDateTime(allInsuredByRecNum.Rows[0][45].ToString().Trim()));//Insured.EffectiveDate
SQLString = "SELECT InsuredRecNum, RecNum FROM Claim WHERE InsuredRecNum = " + rNum;
DataTable iRecNum2ClaimRecNumFromClaim = dbConnect.readDB(SQLString);
rNum = iRecNum2ClaimRecNumFromClaim.Rows[0][1].ToString().Trim();
issueDate = allInsuredByRecNum.Rows[0][45].ToString().Trim();//Insured.EffectiveDate
issueDate = (Convert.ToDateTime(issueDate)).Date.ToString("MM/dd/yyyy");
sex = allInsuredByRecNum.Rows[0][13].ToString().Trim();//Insured.Gender
planCode = allInsuredByRecNum.Rows[0][44].ToString().Trim();//Insured.PlanMnemonic
issueAmt = allInsuredByRecNum.Rows[0][49].ToString().Trim();//Insured.BenefitAmount (Monthly Benefit Amount before Offset)
benefitPeriod = allInsuredByRecNum.Rows[0][50].ToString().Trim();//Insured.BenefitPeriod
if (allInsuredByRecNum.Rows[0][54].ToString().Trim().Length == 2)//Insured.EliminationPeriod
eliminationPeriod = "0" + allInsuredByRecNum.Rows[0][54].ToString().Trim();
else
eliminationPeriod = allInsuredByRecNum.Rows[0][54].ToString().Trim();
premiumAmount = allInsuredByRecNum.Rows[0][48].ToString().Trim();//Insured.AnnualPremium
occupationClass = allInsuredByRecNum.Rows[0][55].ToString().Trim();//Insured.OccupationClass
//select only status = EXEC (0)
SQLString = "SELECT * FROM Offset WHERE ClaimRecNum = " + rNum + " AND Status = 0";
DataTable allOffsetByClaimRecNumAndStatus0 = dbConnect.readDB(SQLString);
offsetAmt = 0;
dblSTDOffsetAmount = 0;
dblRecOffsetAmount = 0;
RECOffsetOcc = "0";
RECOffsetExecuted = "0";
int offsetCount = allOffsetByClaimRecNumAndStatus0.Rows.Count;
if (offsetCount != 0)
{
for (int j = 0; j < offsetCount; j++)
{
//accumulate standard offset (STD) and Recovery offset (REC)
if (allOffsetByClaimRecNumAndStatus0.Rows[0][1].ToString().Trim() == "0")//Offset.Type
{
//Standard Type
dblSTDOffsetAmount += Convert.ToDouble(allOffsetByClaimRecNumAndStatus0.Rows[j][4].ToString().Trim());//Offset.Amount
}
else
{
//Recovery type
dblRecOffsetAmount = Convert.ToDouble(allOffsetByClaimRecNumAndStatus0.Rows[j][4].ToString().Trim());//Offset.Amount
RECOffsetOcc = allOffsetByClaimRecNumAndStatus0.Rows[j][5].ToString().Trim();//Offset.Occurance
RECOffsetExecuted = allOffsetByClaimRecNumAndStatus0.Rows[j][6].ToString().Trim();//Offset.Executed
}//end if
}//end for loop
}//end if
STDOffsetAmount = dblSTDOffsetAmount.ToString();
RECOffsetAmount = dblRecOffsetAmount.ToString();
if (chkIncludePaymentsForCurrentMonth.Checked == true)
SQLString = "SELECT * FROM Payment WHERE InsuredRecNum = " + rNum + " AND IssueDate >= #01/01/" + DateTime.Today.Date.Year + "# AND IssueDate <= #" + DateTime.Today.Date.ToShortDateString() + "#";
else
SQLString = "SELECT * FROM Payment WHERE InsuredRecNum = " + rNum + " AND IssueDate >= #01/01/" + endDate.Substring(endDate.Length - 4) + "# AND IssueDate <= #" + Convert.ToDateTime(endDate).Date.ToShortDateString() + "#";
DataTable allPaymentByIRecNumAndIssDateInRange = dbConnect.readDB(SQLString);
YTDPmt = 0;
if (allPaymentByIRecNumAndIssDateInRange.Rows.Count == 0)
YTDPmt = 0;
else
{
int paymentCount = allPaymentByIRecNumAndIssDateInRange.Rows.Count;
double issAmt;
for (int k = 0; k < paymentCount; k++)
{
issAmt = Convert.ToDouble(allPaymentByIRecNumAndIssDateInRange.Rows[0][30].ToString().Trim());//Payment.IssueAmount
YTDPmt += issAmt;
}// end loop
}//end if
YTDPmts = YTDPmt.ToString();
if (chkIncludePaymentsForCurrentMonth.Checked == true)
SQLString = "SELECT * FROM Payment WHERE ClaimRecNum = " + rNum;
else
SQLString = "SELECT * FROM Payment WHERE ClaimRecNum = " + rNum + " AND IssueDate <= #" + Convert.ToDateTime(endDate).Date.ToShortDateString() + "#";
DataTable allPaymentByRNum = dbConnect.readDB(SQLString);
totalPmt = 0;
if (allPaymentByRNum.Rows.Count == 0)
totalPmt = 0;
else
{
double issAmt = Convert.ToDouble(allPaymentByRNum.Rows[0][30].ToString().Trim());
for (int m = 0; m < allPaymentByRNum.Rows.Count; m++)
{
totalPmt += issAmt;
}
}
allPmts = totalPmt.ToString();
//set spacing for output
string block1 = policy + claim + planCode;
block1 = setSpacing(block1, 28);
string block2 = setSpacing(benefitPeriod, 3) + eliminationPeriod + occupationClass;
block2 = setSpacing(block2, 11);
issueAmt = setSpacing(issueAmt, 8);
STDOffsetAmount = setSpacing(STDOffsetAmount, 8);
RECOffsetAmount = setSpacing(RECOffsetAmount, 8);
RECOffsetOcc = setSpacing(RECOffsetOcc, 3);
RECOffsetExecuted = setSpacing(RECOffsetExecuted, 3);
string block3 = lossDate + age;
block3 = setSpacing(block3, 13);
issueAge = setSpacing(issueAge, 3);
string block4 = issueDate + DOB + sex + onWaiver + premiumAmount;
block4 = setSpacing(block4, 32);
reinsPreNotice = setSpacing(reinsPreNotice, 3);
reinsCeded = setSpacing(reinsCeded, 4);
double ap = Convert.ToDouble(allPmts);
allPmts = ap.ToString("#.#");
allPmts = setSpacing(allPmts, 8);
YTDPmts = setSpacing(YTDPmts, 8);
lName = setSpacing(lName, 19);
fName = fName + " " + mi;
fName = setSpacing(fName, 20);
string block5 = state + direct;
block5 = setSpacing(block5, 10);
ceded = setSpacing(ceded, 8);
WP = setSpacing(WP, 8);
reportedDate = setSpacing(reportedDate, 10);
//save row data for text file
dataOutput = (block1 + block2 + issueAmt + STDOffsetAmount + RECOffsetAmount + RECOffsetOcc + RECOffsetExecuted +
block3 + issueAge + block4 + reinsPreNotice + reinsCeded + allPmts + YTDPmts + lName + fName +
block5 + ceded + WP + reportedDate);
//Write to the output record DI_Extract.txt
sw.WriteLine(dataOutput);
counter++;
pbrRecordsProcessed.Value = counter;
}//end for loop
}//end streamwriter
}//end if
After looking deeper into the code I realized that the connection was trying to open 3 times before it closed. Not sure why I was not getting exceptions all the time but correcting this issue not only sped up the application tremendously it cleared the exception.
I have a web app which reads an excel sheet and adds in 3 columns. Here i service code which reads and write columns.
For the date columns, it is not writing their heading, not any heading for the new columns.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;
using FDBService.AppCode;
using System.IO;
using System.Data.OleDb;
using System.Data;
using Microsoft.Office.Interop.Excel;
namespace FDBService
{
vFileName = string.Concat(vPath, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.TimeOfDay.ToString().Replace(":", "").Substring(0, 6), "_", pUploadfile.fileName);
FileStream FileStream = new FileStream(vFileName, FileMode.Create);
FileStream.Write(pUploadfile.file, 0, pUploadfile.file.Length);
FileStream.Close();
FileStream.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return vFileName;
}
public List<Medicine> ProcessPriceList(string pFileName)
{
List<Medicine> lstReturn = null;
string strConnection = string.Concat("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=", pFileName, ";Extended Properties=", "Excel 8.0;");
System.Data.DataTable dt = new System.Data.DataTable("dtSheet");
try
{
using (OleDbConnection conn = new OleDbConnection(strConnection))
{
conn.Open();
System.Data.DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
List<string> lstSheet = new List<string>();
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))//checks whether row contains '_xlnm#_FilterDatabase' or sheet name(i.e. sheet name always ends with $ sign)
{
lstSheet.Add(drSheet["TABLE_NAME"].ToString());
}
}
using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + lstSheet[0] + "]", conn))
{
//////conn.Open();
da.Fill(dt);
}
}
if (dt != null && dt.Rows.Count > 0)
{
dt.Columns.Add("Unit Price", typeof(string));
dt.Columns.Add("Price", typeof(string));
dt.Columns.Add("Variance", typeof(string));
dt.Columns.Add("PercentVariance", typeof(string));
string vFDBPath = System.Configuration.ConfigurationManager.AppSettings["FDBFilePath"].ToString();
FDB objFDB = null;
string[] strFDB = File.ReadAllLines(vFDBPath);
List<FDB> lstFDB = new List<FDB>();
foreach (string str in strFDB)
{
objFDB = new FDB();
objFDB.NDC = str.Substring(0, 11);
objFDB.PriceType = str.Substring(11, 2);
objFDB.Price = string.Concat(str.Substring(21, 6), ".", str.Substring(27, 5));
objFDB.Date = str.Substring(13, 8);
lstFDB.Add(objFDB);
}
double dPrice = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
string ndc = Convert.ToString(dt.Rows[i][7]);
List<FDB> objLst = (from item in lstFDB
where item.NDC == ndc && item.PriceType == "09"
orderby item.Date descending
select item).ToList();
if (objLst != null)
{
FDB objFirstItem = objLst.FirstOrDefault();
if (objFirstItem != null)
{
if (new DateTime(Convert.ToInt32(objFirstItem.Date.Substring(0, 4)), Convert.ToInt32(objFirstItem.Date.Substring(4, 2)), Convert.ToInt32(objFirstItem.Date.Substring(6, 2))) > Convert.ToDateTime(dt.Rows[i][6]))
{
if (objLst.Count > 1)
{
FDB objSecondItem = objLst[1];
dt.Rows[i]["Unit Price"] = objSecondItem.Price;
dPrice = Convert.ToDouble(objSecondItem.Price) * Convert.ToDouble(dt.Rows[i][13]);
dt.Rows[i]["Price"] = dPrice;
double billPrice = Convert.ToDouble(dt.Rows[i][12]);
dt.Rows[i]["Variance"] = (billPrice - dPrice);
if (dPrice != 0)
{
//////dt.Rows[i]["PercentVariance"] = string.Concat(Math.Round(((billPrice / dPrice) * 100), 0), " %");
dt.Rows[i]["PercentVariance"] = Math.Round(((billPrice / dPrice) * 100), 0);
}
}
}
else
{
dt.Rows[i]["Unit Price"] = objFirstItem.Price;
dPrice = Convert.ToDouble(objFirstItem.Price) * Convert.ToDouble(dt.Rows[i][13]);
dt.Rows[i]["Price"] = dPrice;
double billPrice = Convert.ToDouble(dt.Rows[i][12]);
dt.Rows[i]["Variance"] = (billPrice - dPrice);
if (dPrice != 0)
{
//////dt.Rows[i]["PercentVariance"] = string.Concat(Math.Round(((billPrice / dPrice) * 100), 0), " %");
dt.Rows[i]["PercentVariance"] = Math.Round(((billPrice / dPrice) * 100), 0);
}
}
}
}
}
catch (Exception ex)
{
//////throw ex;
}
}
lstReturn = new List<Medicine>();
Medicine objMedicine = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
try
{
FileInfo file = new FileInfo(pFileName);
if (file.Exists)
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
workbook = excelApp.Workbooks.Open(pFileName, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
sheets = workbook.Sheets;
//check columns exist
foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in sheets)
{
Console.WriteLine(sheet.Name);
sheet.Select(Type.Missing);
/////////
lstSheetNames.Add(sheet.Name);
/////////
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "Updated";
/////////////////////////////////////////
string strConnection = string.Concat("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=", pFileName, ";Extended Properties=", "Excel 8.0;");
System.Data.DataTable dt = new System.Data.DataTable("dtSheet");
try
{
using (OleDbConnection conn = new OleDbConnection(strConnection))
{
using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + lstSheetNames[0] + "$]", conn))
{
conn.Open();
da.Fill(dt);
}
}
}
catch (Exception ex)
{
}
dt.Columns.Add("Unit Price", typeof(string));
dt.Columns.Add("Price", typeof(string));
dt.Columns.Add("Variance", typeof(string));
dt.Columns.Add("PercentVariance", typeof(string));
FDB objFDB = null;
string[] strFDB = File.ReadAllLines(System.Configuration.ConfigurationManager.AppSettings["FDBFilePath"].ToString());
List<FDB> lstFDB = new List<FDB>();
foreach (string str in strFDB)
{
objFDB = new FDB();
objFDB.NDC = str.Substring(0, 11);
objFDB.PriceType = str.Substring(11, 2);
objFDB.Price = string.Concat(str.Substring(21, 6), ".", str.Substring(27, 5));
objFDB.Date = str.Substring(13, 8);
lstFDB.Add(objFDB);
}
double dPrice = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
string ndc = Convert.ToString(dt.Rows[i][7]);
List<FDB> objLst = (from item in lstFDB
where item.NDC == ndc && item.PriceType == "09"
orderby item.Date descending
select item).ToList();
if (objLst != null)
{
FDB objFirstItem = objLst.FirstOrDefault();
if (objFirstItem != null)
{
if (new DateTime(Convert.ToInt32(objFirstItem.Date.Substring(0, 4)), Convert.ToInt32(objFirstItem.Date.Substring(4, 2)), Convert.ToInt32(objFirstItem.Date.Substring(6, 2))) > Convert.ToDateTime(dt.Rows[i][6]))
{
if (objLst.Count > 1)
{
FDB objSecondItem = objLst[1];
dt.Rows[i]["Unit Price"] = objSecondItem.Price;
dPrice = Convert.ToDouble(objSecondItem.Price) * Convert.ToDouble(dt.Rows[i][13]);
dt.Rows[i]["Price"] = dPrice;
double billPrice = Convert.ToDouble(dt.Rows[i][12]);
dt.Rows[i]["Variance"] = (billPrice - dPrice);
if (dPrice != 0)
{
dt.Rows[i]["PercentVariance"] = string.Concat(Math.Round(((billPrice / dPrice) * 100), 0), " %");
}
}
}
else
{
dt.Rows[i]["Unit Price"] = objFirstItem.Price;
dPrice = Convert.ToDouble(objFirstItem.Price) * Convert.ToDouble(dt.Rows[i][13]);
dt.Rows[i]["Price"] = dPrice;
double billPrice = Convert.ToDouble(dt.Rows[i][12]);
dt.Rows[i]["Variance"] = (billPrice - dPrice);
if (dPrice != 0)
{
dt.Rows[i]["PercentVariance"] = string.Concat(Math.Round(((billPrice / dPrice) * 100), 0), " %");
}
}
}
}
}
catch (Exception ex)
{
//////MessageBox.Show(ex.ToString());
}
}
//////for (int i = 0; i < dt.Columns.Count; i++)
//////{
////// newSheet.Cells[1, i + 1] = dt.Columns[i].Caption;
////// newSheet.Cells[1, i + 1].Font.Bold = true;
////// //////newSheet.Cells[1, i + 1].Interior.Color = Color.FromArgb(191, 191, 191);
//////}
int rowCount = 1;
foreach (System.Data.DataRow dr in dt.Rows)
{
rowCount += 1;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
newSheet.Cells[rowCount, i] = dr[i - 1].ToString();
}
}
//////////////////////////////////////////
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
////////////////////////////////
lstReturn = new List<Medicine>();
Medicine objMedicine = null;
for (int i = 0; i < dt.Rows.Count; i++)
{
try
{
objMedicine = new Medicine();
objMedicine.FacID = dt.Rows[i][0] != DBNull.Value ? Convert.ToString(dt.Rows[i][0]) : "";
objMedicine.PatID = dt.Rows[i][1] != DBNull.Value ? Convert.ToString(dt.Rows[i][1]) : "";
objMedicine.Patient = dt.Rows[i][2] != DBNull.Value ? Convert.ToString(dt.Rows[i][2]) : "";
objMedicine.PriceCd = dt.Rows[i][3] != DBNull.Value ? Convert.ToString(dt.Rows[i][3]) : "";
objMedicine.InvoiceGrp = dt.Rows[i][4] != DBNull.Value ? Convert.ToString(dt.Rows[i][4]) : "";
objMedicine.RxNo = dt.Rows[i][5] != DBNull.Value ? Convert.ToString(dt.Rows[i][5]) : "";
objMedicine.FillDate = dt.Rows[i][6] != DBNull.Value ? Convert.ToString(dt.Rows[i][6]) : "";
objMedicine.NDC = dt.Rows[i][7] != DBNull.Value ? Convert.ToString(dt.Rows[i][7]) : "";
objMedicine.Drug = dt.Rows[i][8] != DBNull.Value ? Convert.ToString(dt.Rows[i][8]) : "";
objMedicine.BrandGen = dt.Rows[i][9] != DBNull.Value ? Convert.ToString(dt.Rows[i][9]) : "";
objMedicine.RxOTC = dt.Rows[i][10] != DBNull.Value ? Convert.ToString(dt.Rows[i][10]) : "";
objMedicine.FWBillDate = dt.Rows[i][11] != DBNull.Value ? Convert.ToString(dt.Rows[i][11]) : "";
objMedicine.FWBillAmt = dt.Rows[i][12] != DBNull.Value ? Convert.ToString(dt.Rows[i][12]) : "";
objMedicine.Quantity = dt.Rows[i][13] != DBNull.Value ? Convert.ToString(dt.Rows[i][13]) : "";
objMedicine.UnitPrice = dt.Rows[i][14] != DBNull.Value ? Convert.ToString(dt.Rows[i][14]) : "";
objMedicine.Price = dt.Rows[i][15] != DBNull.Value ? Convert.ToString(dt.Rows[i][15]) : "";
objMedicine.Variance = dt.Rows[i][16] != DBNull.Value ? Convert.ToString(dt.Rows[i][16]) : "";
objMedicine.PercentVariance = dt.Rows[i][17] != DBNull.Value ? Convert.ToString(dt.Rows[i][17]) : "";
lstReturn.Add(objMedicine);
}
catch (Exception ex)
{
}
}
}
}
Interop is NOT supported in sever-scenarios (like ASP.NET, IIS, WCF, Windows Service etc.) by MS.
There are many options to read/edit/create Excel files without Interop:
MS provides the free OpenXML SDK V 2.0 - see http://msdn.microsoft.com/en-us/library/bb448854%28office.14%29.aspx (XLSX only)
This can read+write MS Office files (including Excel).
Another free option see http://www.codeproject.com/KB/office/OpenXML.aspx (XLSX only)
IF you need more like handling older Excel versions (like XLS, not only XLSX), rendering, creating PDFs, formulas etc. then there are different free and commercial libraries like ClosedXML (free, XLSX only), EPPlus (free, XLSX only), Aspose.Cells, SpreadsheetGear, LibXL and Flexcel etc.