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
Related
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
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;
}
}
}
I'm doing project in C# that read from a video file and convert it to subtitle text, but i want to get the start time for each text line so it can be shown in the video at the right time, i tried the AudioPosition but it not working well, is there a away to do this?
using System;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading.Tasks;
namespace project
{
public partial class Form1 : Form
{
StringBuilder sb = new StringBuilder();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string[] tokens;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "WAV|*.wav";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
}
SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
Grammar gr = new DictationGrammar();
sre.LoadGrammar(gr);
sre.SetInputToWaveFile(#openFileDialog1.FileName);
while (true)
{
try
{
var recText = sre.Recognize();
sb.Append(recText.Audio.AudioPosition + " * ");
textBox4.Text = sb.ToString();
tokens = sb.ToString().Split('#');
for (int i = 0; i < tokens.Length - 1; i++)
{
textBox2.AppendText(tokens.Length.ToString());
textBox2.AppendText(i+" - "+tokens[i]);
textBox2.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
break;
}
}
}
Read them back in app constructor and also maybe in other places in program.
I have a new form i created with some checkboxes:
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 Options
{
public partial class OptionsMenuForm : Form
{
public OptionsMenuForm()
{
InitializeComponent();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
Settings.downloadonstart = true;
}
else
{
Settings.downloadonstart = false;
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
if (checkBox2.Checked)
{
Settings.loadonstart = true;
}
else
{
Settings.loadonstart = false;
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
Settings.startminimized = true;
}
else
{
Settings.startminimized = false;
}
}
private void checkBox4_CheckedChanged(object sender, EventArgs e)
{
if (checkBox4.Checked)
{
Settings.displaynotifications = true;
}
else
{
Settings.displaynotifications = false;
}
}
}
}
Now i want to save each time the state of one/any of the checkboxes.
I also added a class i'm using th pass the variables between the new form and form1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Options
{
class Settings
{
public static bool downloadonstart;
public static bool loadonstart;
public static bool startminimized;
public static bool displaynotifications;
}
}
Now how can i use this in form1 by saving the settings to a text file ?
For example in the text file the content will be something like:
CheckBox1 = true
CheckBox2 = false
CheckBox3 = false
CheckBox4 = true
And then if i change the state of one of them it will write it in the text file:
CheckBox1 = false
CheckBox2 = false
CheckBox3 = true
CheckBox4 = true
In form1 top i added
string settingsFile = "settings.txt";
string settingsFileDirectory = "\\settings";
StreamWriter writetosettingsfile;
Then in constructor
settingsFileDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) +
settingsFileDirectory;
if (!Directory.Exists(settingsFileDirectory))
{
Directory.CreateDirectory(settingsFileDirectory);
}
I know the app it self have a settings in the properties but i wanted to use a text file this time since i have many settings and i might have more later.
Or using the settings in the app in properties i did:
But now how do i use with it in my program to save every checkbox state in the new form and then using it in form1 ?
You can use json.net
Something like this to save the data
private void Form1_Load(object sender, EventArgs e)
{
checkBox1.CheckedChanged += checkBox_CheckedChanged;
checkBox2.CheckedChanged += checkBox_CheckedChanged;
checkBox3.CheckedChanged += checkBox_CheckedChanged;
checkBox4.CheckedChanged += checkBox_CheckedChanged;
}
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
var settings = new Settings();
settings.downloadonstart = checkBox1.Checked;
settings.loadonstart = checkBox2.Checked;
settings.startminimized = checkBox3.Checked;
settings.displaynotifications = checkBox4.Checked;
File.WriteAllText(#"c:\configfile.json", JsonConvert.SerializeObject(settings));
}
You can read the file like this
Settings settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(#"c:\configfile.json"));
Documentation:
http://www.newtonsoft.com/json/help/html/Introduction.htm
public OptionsMenuForm()
{
InitializeComponent();
//Read the settings from a file with comma delimited 1's and 0's or whatever you like
string[] values = System.IO.File.ReadAllText("c:\temp\a.txt").Split(',');
checkBox1.Checked = Convert.ToBoolean(Convert.ToInt32(values[0]));
checkBox2.Checked = Convert.ToBoolean(Convert.ToInt32(values[1]));;
//On checkbox changes save the settings
checkBox1.CheckedChanged +=SaveSettings;
checkBox2.CheckedChanged +=SaveSettings;
}
public void SaveSettings(object sender,EventArgs e)
{
StringBuilder sbValues = new StringBuilder();
int i = 0;
i = checkBox1.Checked ? 1 : 0;
sbValues.Append(i.ToString() + ",");
i = checkBox2.Checked ? 1 : 0;
sbValues.Append(i.ToString() + ",");
System.IO.File.WriteAllText("c:\temp\a.txt",sbValues.ToString());
}
It is recommended that you use XML when using the .NET framework.
public static void ConvertStringToXmlList()
{
XElement xml = new XElement
(
"Items",
(
from x in [YourList] select new XElement("Item", x)
)
);
XDocument doc = new XDocument
(
xml
);
doc.Save(Environment.CurrentDirectory + "/settings.xml");
}
var xmlReader = new XmlTextReader("settings.xml");
while (xmlReader.Read())
{
switch (reader.NodeType)
{
case [nodetype]:
// Code here
break;
}
}
Also, instead of creating the same event for all four checkbox's, just use 1.
Inside of the single event put:
ckCheckBox1.Checked = !ckCheckBox1.Checked;
All of a sudden my form window has begun to close as soon as the application is launched. There's nothing in the output window that gives a hint as to what could be causing it and there are no errors thrown at me either. Does anybody have any ideas?
I've provided to form's class.
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 ProjectBoardManagement {
public partial class CreateBoard : Form {
Functions funcs = new Functions();
public CreateBoard() {
InitializeComponent();
}
private void CreateBoardButton_Click(object sender, EventArgs e) {
String BoardName = BoardNameText.Text;
String Pages = "";
String Labels = "";
foreach (ListViewItem i in PageNameList.Items) {
Pages = (Pages + i.Name.ToString() + ",");
}
foreach (ListViewItem i in LabelNameList.Items) {
Labels = (Labels + i.Name.ToString() + ",");
}
String BoardFile = ("board_" + BoardName + ".txt");
funcs.SaveSetting(BoardFile, "name", BoardName);
funcs.SaveSetting(BoardFile, "pages", Pages);
funcs.SaveSetting(BoardFile, "labels", Labels);
FormManagement.CreateBoard.Hide();
FormManagement.BoardList.LoadBoardList();
}
private void PageNameButtonAdd_Click(object sender, EventArgs e) {
String pagename = PageNameText.Text;
if (pagename != "") {
PageNameList.Items.Add(pagename);
}
PageNameText.Text = "";
}
private void LabelNameButtonAdd_Click(object sender, EventArgs e) {
String labelname = LabelNameText.Text;
if (labelname != "") {
LabelNameList.Items.Add(labelname);
}
LabelNameText.Text = "";
}
}
}
Obvious first thing to do - run it in Debug mode and stop execution on all exceptions. This should give you enough information on how to go from there.
Otherwise Functions funcs = new Functions(); looks suspicious.