I'm having trouble updating two excel files side by side - c#

By clicking on the "Synchronize" button we will collect the stock numbers of the 2 tables and print them on the stock number of the 1st table.
I have two excel files side by side and I'm having trouble updating them
(addition + transfer).
Synchronize
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Excel;
using Microsoft.Office.Core;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet ds;
DataSet ds2;
OpenFileDialog of;
OpenFileDialog ofl;
FileStream fs;
FileStream fst;
IExcelDataReader okuyucu;
IExcelDataReader okuyucu1;
DataTable dt;
DataTable dts;
DataRow new_data_row;
int adet;
int adet2;
int StokNo1;
int StokNo2;
private void button3_Click(object sender, EventArgs e)//Synchronize Button
{
int Adet = Int32.Parse(dataGridView1.Columns[2].Index.ToString());
int Adet2 = Int32.Parse(dataGridView2.Columns[2].Index.ToString());
int StokNo1 = Int32.Parse(dataGridView1.Columns[0].Index.ToString());
int StokNo2 = Int32.Parse(dataGridView2.Columns[0].Index.ToString());
foreach (DataTable dt in ds.Tables)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
StokNo1 = Int32.Parse(dataGridView1.Columns[0].Index.ToString());//The StokNo belonging to DataGridWiew1.
Adet = Int32.Parse(dataGridView1.Columns[2].Index.ToString());//The number belonging to DataGridWiew1.
}
}
foreach (DataTable dt2 in ds2.Tables)
{
for (int j = 0; j < ds2.Tables.Count; j++)
{
StokNo2 = Int32.Parse(dataGridView2.Columns[0].Index.ToString());//The StokNo belonging to DataGridWiew2.
Adet2 = Int32.Parse(dataGridView2.Columns[2].Index.ToString());//The number belonging to DataGridWiew2.
}
}
if ((StokNo1 == StokNo2))//StokNo is Equal
{
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
int toplam = adet + adet2;
ds.Tables[0].Rows.Add(toplam);
}
}
else
{
ds.Tables[0].Rows.Add();//If stokno is not equal add to the last listed
}
}
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Excel|*.xls";
save.OverwritePrompt = true;
save.CreatePrompt = true;
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter kayıt = new StreamWriter(save.FileName);
kayıt.WriteLine(dataGridView1.ToString());
kayıt.Close();
}
}
}
}
if the stock number is equal to add to list , I want to update the number according to the stock code I want to add it at the end if the stock code is different

Related

c# windows form System.Runtime.InteropServices.COMException

I am trying to write c # code that automates the process of filling out Word templates. I use DataGridView because I don't know how many types of elements I need to replace. Upon completion of work, it throws an error System.Runtime.InteropServices.COMException: "The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)" thanks
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Word = Microsoft.Office.Interop.Word;
namespace Anya_v_0._8
{
public partial class Form1 : Form
{
//-------------------struct---------------------//
public struct name
{
public string teg;
public string change;
public name(String _teg, string _change)
{
teg = _teg;
change = _change;
}
}
//----------------------------------------//
List<name> names = new List<name>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//-------------------table------------//
DataTable table = new DataTable();
table.Columns.Add("Тэг", typeof(string));
table.Columns.Add("Название", typeof(string));
for (int i = 0; i < names.Count; i++)
{
table.Rows.Add(names[i].teg, names[i].change);
}
dataGridView1.DataSource = table;
//-------------------------------//
}
private void click_start_Click(object sender, EventArgs e) {
String vhod = inputBox.Text;
String uhod = outputBox.Text;
var wordApp = new Word.Application();
wordApp.Visible = false;
var wordDocument = wordApp.Documents.Open(vhod);
for (int i = 0; i < dataGridView1.RowCount; i++)
{
for (int j = 0; j < dataGridView1.ColumnCount; j++)
{
object a = dataGridView1.Rows[i].Cells[j].ToString();
object b = dataGridView1.Rows[i+1].Cells[j].ToString();
ReplaceWordStub(a, b, wordDocument);
}
}
wordDocument.SaveAs(uhod);
}
private void ReplaceWordStub(object stubToReplace, object text, Word.Document wordDocument)
{
var range = wordDocument.Content;
range.Find.ClearFormatting();
range.Find.Execute(FindText: stubToReplace, ReplaceWith: text);
}
public void inputBox_TextChanged(object sender, EventArgs e)
{
}
}
}
Your solution needs to have the word installed to work, you could use OpenXML instead.
But considering you want to keep this dependency on Word, check if the Remote Procedure Call is started and running on your windows services

Can't add to database with C# and ADO.NET

I want to write a program that save all the data from a .csv into a database.
I use a service-based database.
But when I want to use the addtoTablesName like what I used to do and I learned at university, it suddenly throws an error.
This is my code:
class Program
{
static void Main(string[] args)
{
Database1Entities1 dbb = new Database1Entities1();//object database
excel.Application xlApp;
excel.Workbook xlWb;
excel._Worksheet xlWs;
excel.Range xlRange;
excel.Application xlApp1;
excel.Workbook xlWb1;
excel._Worksheet xlWs1;
excel.Range xlRange1;
int rowFile = 0;
int colFile = 0;
string[][] dataFile;
DateTime date = DateTime.Now;
string tgl = date.Date.ToString("dd");
string bln = date.Month.ToString("d2");
string thn = date.Year.ToString();
string tglskrg = thn+bln+tgl;
string[] items;
DateTime otime2 = DateTime.ParseExact(tglskrg, "yyyyMMdd", null);
xlApp = new excel.Application();
string[] filesindirectory = Directory.GetDirectories(#"C:\Users\u532246\Desktop\TRAVELOKA");
foreach (string files in filesindirectory)
{
string name = Path.GetFileName(files);
string subname = name.Substring(10, 8);
DateTime subTime = DateTime.ParseExact(subname, "yyyyMMdd", null);
TimeSpan span = otime2.Subtract(subTime);
if(span.Days < 2)
{
// Console.WriteLine(files);
foreach(string subfiles in Directory.GetFiles(files))
{
xlWb = xlApp.Workbooks.Open(subfiles);
xlWs = xlWb.Sheets[1];
xlRange = xlWs.UsedRange;
rowFile = xlRange.Rows.Count;
colFile = xlRange.Columns.Count;
dataFile = new string[rowFile][];
for(int i = 0; i < dataFile.Length; i++)
{
dataFile[i] = new string[colFile];
}
for(int i = 0; i<rowFile;i++)
{
for(int j = 0; i<colFile;j++)
{
try
{
dataFile[i][j] = xlWs.Cells[i + 1, j + 1].value2.ToString();
//MessageBox.Show(dataMapping[i][j]);
}
catch (Exception ee)
{
dataFile[i][j] = "";
}
}
}
CMRTable cmr = new CMRTable();
for(int i = 0; i < rowFile; i++)
{
items = dataFile[i][0].Split(';');
cmr.Id = i + 1;
cmr.Merchant_Name = items[1];
cmr.Sett_Date = items[2];
cmr.Proc_Date = items[3];
cmr.Mid = items[4];
cmr.CardType = items[5];
cmr.Trx_Date = items[6];
cmr.Jam_Trx = items[7];
cmr.Auth = items[8];
cmr.CardNo = items[9];
cmr.Trx_Type = items[10];
cmr.Amount = items[11];
cmr.Rate = items[12];
cmr.Disc_Amt = items[13];
cmr.Tenor_Ins = items[14];
cmr.Rate_Ins = items[15];
cmr.Disc_Ins = items[16];
cmr.Net_Amt = items[17];
cmr.Purchase_Id = items[18];
cmr.Mechant_Descriptor = items[19];
dbb.AddToCMRTables(cmr); #I CANT USE THIS FUNCTION , DONT KNOW WHY
dbb.SaveChanges();
}
Console.WriteLine(subfiles);
}
}
}
}
}
Can someone help me? I think I already do everything exactly like I did in university ..
EDIT: here's the error I get:
Database1Entities1 does not contain a definition for AddToCMRTables and no accessible extension method AddToCMRTables accepting a first argument of type Database1Entities1 could be found
I copy what i used to do in university (here's the code)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{//dipakai ketika ingin menginsert data ke database.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
displayData();
}
Database1Entities db = new Database1Entities();//object database
private void displayData()
{
var query = from x
in db.MsStudents
select x;
dataGridView1.DataSource = query;
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
txtID.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value.ToString();
txtName.Text = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value.ToString();
}//buat ngeklik yg ada di data grid view
private void txtSearch_TextChanged(object sender, EventArgs e)
{
search(txtSearch.Text);
}
public void search(string kata) {
var query = from x
in db.MsStudents
where x.Name.Contains(kata)//apa yang muncul di kotak search itu di select
select x;
dataGridView1.DataSource = query;
}//function buat search
private void btnInsert_Click(object sender, EventArgs e)
{
MsStudent student = new MsStudent();
student.ID = Int32.Parse(txtID.Text);
student.Name = txtName.Text;
db.AddToMsStudents(student);
db.SaveChanges();
displayData();
}
private void btnReset_Click(object sender, EventArgs e)
{
foreach (Control a in this.Controls)
{
if (a.GetType() == typeof(TextBox))
{
a.Text = "";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

Import from *.txt to DataGridView without 2 columns

Sorry for my English. I'm newbie in c#. I have quuestion. I have file txt with data:
20160101 PL01 000000000000000003 PL02 TO 0000000001 1.720 0000000001 0000000002
Finnaly i want import this data to DataGridView but only columns 1,4,7,8,9 without columns 2,3,5 and 6.
I try on start Import all data but I have error
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\terrazo\\Desktop\\test1.txt");
string[] columnnames = file.ReadLine().Split(' ');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(' ');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
}
}
}
Can anyone help me how import data from txt file without several columns??
thx for all answer.
I have gone through your code and also the error you are facing and came to know that your text file while taken in account also have null spaces or multiple blank space and when you are split it on whitespace base it will also have some null values. I have updated your code for the same please try it and in case you face some problem please feel free to ask me.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\terrazo\\Desktop\\test1.txt");
string[] columnnames = file.ReadLine().Split(' ');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
if (c != "")
{
dt.Columns.Add(c);
}
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split(' ');
for (int i = 0; i < values.Length; i++)
{
if (values[i] != "")
{
dr[i] = values[i];
}
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
}
}
}

C# Windows Application LOC_Counter

Hey I want to create a windows application that should display the total lines, Blank lines and commented lines. I am able to calculate Total Lines, Can any one help me with the logic for blank lines and commented lines!
I want to count the Lines Of Code, for any file, i.e .html, .css, .cs, etc.
Also if possible I want the result to be exported to a Excel File!
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace Line_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
textbox1.Clear();
textbox2.Clear();
if (ofd.ShowDialog() == DialogResult.OK)
{
string strFilename = ofd.FileName;
textbox1.Text = Path.GetFileName(strFilename);
StreamReader sr = File.OpenText(strFilename);
int nLineCount = 0;
while (sr.ReadLine() != null)
{
nLineCount++;
}
textbox1.Text = nLineCount.ToString("0,0");
sr.Close();
}
}
private void txtFileName_TextChanged(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I want more text boxes that should display count of blank lines, Commented lines, and finally the total count (i.e. subtracting the no. of blank lines and commented lines from total no of lines)
If Possible single button_click for each or all in one.enter image description here
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace LOC_Counter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void getFileList(string directory)
{
string[] dirs = Directory.GetDirectories(directory);
foreach (string dir in dirs)
{
getFileList(dir);
}
string[] files = Directory.GetFiles(directory);
foreach (string file in files)
{
StreamReader sr = File.OpenText(file);
int nLineCount = 0;
string str = string.Empty;
while (!sr.EndOfStream)
{
str = sr.ReadLine();
if (str != null && str.Length > 0 && (str.Length > 2 && str.Substring(0, 2) != "//") && (str.Length > 3 && str.Substring(0, 4) != "<!--"))
nLineCount++;
}
lstbxResult.Items.Add(file + " Line count - " + nLineCount);
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
lstbxResult.Items.Clear();
getFileList(FBD.SelectedPath);
}
}
public static void ExportToExcel(ListBox lst, string excel_file)
{
int cols;
//open file
StreamWriter wr = new StreamWriter(excel_file);
//write rows to excel file
for (int i = 0; i < (lst.Items.Count - 1); i++)
{
wr.Write(lst.Items[i].ToString() + "\t");
wr.WriteLine();
}
//close file
wr.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Convert string to double from combobox

I am having a real difficulty getting a string that is being returned from a combobox to convert to a double. I have done some research online and I believe that it should be working. I keep getting user exceptions.
Specifically, I am having an issue with the following part of my code:
private void cboBeverage_SelectedIndexChanged(object sender, EventArgs e)
{
string tempString = cboBeverage.SelectedValue.ToString();
double tempPrice = Convert.ToDouble(tempString);
Calculations(tempPrice);
}
Here is my entire code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace JO_BillCalculator
{
public partial class Form1 : Form
{
double subtotal = 0.00;
double tax = 6.875;
double total = 0.00;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Add data to dtBeverage datatable
DataTable dtBeverage = new DataTable();
DataColumn dc1Beverage = new DataColumn("ItemBeverage");
DataColumn dc2Beverage = new DataColumn("PriceBeverage");
dtBeverage.Columns.Add(dc1Beverage);
dtBeverage.Columns.Add(dc2Beverage);
dtBeverage.Rows.Add("", "0.00");
dtBeverage.Rows.Add("Milk", "1.50");
dtBeverage.Rows.Add("Juice", "2.50");
dtBeverage.Rows.Add("Mineral Water", "2.95");
dtBeverage.Rows.Add("Coffee", "1.25");
dtBeverage.Rows.Add("Tea", "1.50");
dtBeverage.Rows.Add("Soda", "1.95");
//Display data in correct combobox
cboBeverage.DataSource = dtBeverage;
cboBeverage.DisplayMember = "ItemBeverage";
cboBeverage.ValueMember = "PriceBeverage";
//Add data to dtAppitizer datatable
DataTable dtAppitizer = new DataTable();
DataColumn dc1Appitizer = new DataColumn("ItemAppitizer");
DataColumn dc2Appitizer = new DataColumn("PriceAppitizer");
dtAppitizer.Columns.Add(dc1Appitizer);
dtAppitizer.Columns.Add(dc2Appitizer);
dtAppitizer.Rows.Add("", "0.00");
dtAppitizer.Rows.Add("Buffalo Wings", "5.95");
dtAppitizer.Rows.Add("Buffalo Fingers", "6.95");
dtAppitizer.Rows.Add("Potato Skins", "8.95");
dtAppitizer.Rows.Add("Nachos", "8.95");
dtAppitizer.Rows.Add("Mushroom Caps", "10.95");
dtAppitizer.Rows.Add("Shrimp Cocktail", "12.95");
dtAppitizer.Rows.Add("Chips and Salsa", "6.95");
//Display data in correct combobox
cboAppetizer.DataSource = dtAppitizer;
cboAppetizer.DisplayMember = "ItemAppitizer";
cboAppetizer.ValueMember = "PriceAppitizer";
//Add data to dtMainCourse datatable
DataTable dtMainCourse = new DataTable();
DataColumn dc1MainCourse = new DataColumn("ItemMainCourse");
DataColumn dc2MainCourse = new DataColumn("PriceMainCourse");
dtMainCourse.Columns.Add(dc1MainCourse);
dtMainCourse.Columns.Add(dc2MainCourse);
dtMainCourse.Rows.Add("", "0.00");
dtMainCourse.Rows.Add("Chicken Alfredo", "13.95");
dtMainCourse.Rows.Add("Chicken Picatta", "13.95");
dtMainCourse.Rows.Add("Turkey Club", "11.95");
dtMainCourse.Rows.Add("Lobster Pie", "19.95");
dtMainCourse.Rows.Add("Prime Rib", "20.95");
dtMainCourse.Rows.Add("Shrimp Scampi", "18.95");
dtMainCourse.Rows.Add("Turkey Dinner", "13.95");
dtMainCourse.Rows.Add("Stuffed Chicken", "14.95");
dtMainCourse.Rows.Add("Seafood Alfredo", "15.95");
//Display data in correct combobox
cboMainCourse.DataSource = dtMainCourse;
cboMainCourse.DisplayMember = "ItemMainCourse";
cboMainCourse.ValueMember = "PriceMainCourse";
//Add data to dtDessert datatable
DataTable dtDessert = new DataTable();
DataColumn dc1Dessert = new DataColumn("ItemDessert");
DataColumn dc2Dessert = new DataColumn("PriceDessert");
dtDessert.Columns.Add(dc1Dessert);
dtDessert.Columns.Add(dc2Dessert);
dtDessert.Rows.Add("", "0.00");
dtDessert.Rows.Add("Apple Pie", "5.95");
dtDessert.Rows.Add("Sundae", "3.95");
dtDessert.Rows.Add("Carrot Cake", "5.95");
dtDessert.Rows.Add("Mud Pie", "4.95");
dtDessert.Rows.Add("Apple Crisp", "5.95");
//Display data in correct combobox
cboDessert.DataSource = dtDessert;
cboDessert.DisplayMember = "ItemDessert";
cboDessert.ValueMember = "PriceDessert";
}
private void cboBeverage_SelectedIndexChanged(object sender, EventArgs e)
{
string tempString = cboBeverage.SelectedValue.ToString();
double tempPrice = Convert.ToDouble(tempString);
Calculations(tempPrice);
}
private void cboAppetizer_SelectedIndexChanged(object sender, EventArgs e)
{
cboAppetizer.SelectedIndex = 0;
}
private void cboMainCourse_SelectedIndexChanged(object sender, EventArgs e)
{
cboMainCourse.SelectedIndex = 0;
}
private void cboDessert_SelectedIndexChanged(object sender, EventArgs e)
{
cboDessert.SelectedIndex = 0;
}
private void Calculations(double price)
{
}
}
}
use selectedItem insted of SelectedValue
DataRow selectedDataRow = ((DataRowView)cboBeverage.SelectedItem).Row;
double tempPrice = Convert.ToDouble(selectedDataRow["PriceBeverage"]);
Calculations(tempPrice);

Categories