function orderInfo.Selected is not regconized - c#

I'm implementing the code from the book to create a customized action pane in Excel
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.VisualStudio.OfficeTools.Interop.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
namespace ExcelWorkbook1
{
public partial class Sheet1
{
public Button customerButton = new Button();
public Button inventoryButton = new Button();
private void Sheet1_Startup(object sender, EventArgs e)
{
customerButton.Text = "Select a customer...";
inventoryButton.Text = "Check inventory...";
this.orderInfo.Selected +=
new Excel.DocEvents_SelectionChangeEventHandler(
OrderInfo_Selected);
this.orderInfo.Deselected +=
new Excel.DocEvents_SelectionChangeEventHandler(
OrderInfo_Deselected);
this.customerInfo.Selected +=
new Excel.DocEvents_SelectionChangeEventHandler(
CustomerInfo_Selected);
this.customerInfo.Deselected +=
new Excel.DocEvents_SelectionChangeEventHandler(
CustomerInfo_Deselected);
}
#region VSTO Designer generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Sheet1_Startup);
}
#endregion
void OrderInfo_Selected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Add(inventoryButton);
}
void OrderInfo_Deselected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Remove(inventoryButton);
}
void CustomerInfo_Selected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Add(customerButton);
}
void CustomerInfo_Deselected(Excel.Range target)
{
Globals.ThisWorkbook.ActionsPane.Controls.Remove(customerButton);
}
}
}
However
the code this.order.Selected' is not regconized
Do you have any suggestion for me?
Thanks

Do you have a named range in your Sheet1 with name orderInfo?
If yes, is it generated in the code-behind? (Sheet1.Designer.cs)
Notice, that you misspeled the name of your member in the last sentence: should be 'this.orderInfo.Selected'

Related

Fill text in email message editor after New/Reply/ReplyAll events in Outlook VSTO C#

currently I am creating an Outlook plugin to Add predefined text whenever user compose a new mail OR Reply OR Reply All to a mail message.
I took reference from Microsoft tutorials and created this code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Windows.Forms;
namespace VSTO_Outlook_fetch_New_Rely_Reply_All_events
{
public partial class ThisAddIn
{
private Outlook.Application _application = null;
Outlook.Inspectors inspectors;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
_application = Globals.ThisAddIn.Application;
_application.ItemLoad += new Outlook.ApplicationEvents_11_ItemLoadEventHandler(_application_ItemLoad);
inspectors = this.Application.Inspectors;
inspectors.NewInspector +=
new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
Outlook.MailItem mi = null;
private void GenerateItemMessage(object item, string operation)
{
mi = item as Outlook.MailItem;
MessageBox.Show(String.Format("MailItem {0} : ", operation));
MessageBox.Show(String.Format("To : {0}", mi.To));
mi.Body = "Hi \n" + mi.Body;
}
private void ThisAddIn_ReplyAll(object item, ref bool cancel)
{
GenerateItemMessage(item, "ReplyToAll");
}
private void ThisAddIn_Reply(object item, ref bool cancel)
{
GenerateItemMessage(item, "Reply");
}
Outlook.ItemEvents_10_Event _item;
private void _application_ItemLoad(object Item)
{
_item = (Outlook.ItemEvents_10_Event)Item;
_item.ReplyAll += new Outlook.ItemEvents_10_ReplyAllEventHandler(ThisAddIn_ReplyAll);
_item.Reply += new Outlook.ItemEvents_10_ReplyEventHandler(ThisAddIn_Reply);
}
void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
{
Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
if (mailItem != null)
{
if (mailItem.EntryID == null)
{
mailItem.Body = "This text was added by using code";
}
}
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
The issues here are, when a reply/reply all event triggers, the text get inserted to the mail body to which I am replying(Not inside new mail body which is to be sent).
And the text is getting inserted at the last of body(After Signature). I want to it to be at the starting of new mail/reply.
Can anybody help me please? Also, how I can improve this code?

Cannot enter text from class to textbox in form

Cannot enter text from class to textbox in form.
We set a keypress event in the MyTreeView class.
The text box cannot contain characters.
What should I do?
*set of textBox1.
*Change Modifiers for textBox1 properties from private to public
*Change keypress event from private to public
*(It didn't work well, so I keep it private now.)
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.Diagnostics;
namespace treeview
{
public partial class Form1 : System.Windows.Forms.Form
{
MyTreeView m_tree_view = new MyTreeView();
public Form1()
{
try
{
InitializeComponent();
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];
m_tree_view.Location = new System.Drawing.Point(0, 0);
m_tree_view.Size = ClientSize;
m_tree_view.AllowDrop = true;
tree1[0] = new System.Windows.Forms.TreeNode("TreeNode1");
tree1[1] = new System.Windows.Forms.TreeNode("TreeNode2");
m_tree_view.Nodes.Add("Node1");
Controls.Add(m_tree_view);
}
catch
{
}
}
//This is the code I added.
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class MyTreeView : System.Windows.Forms.TreeView
{
public MyTreeView()
{
try
{
//This is the code I added.
KeyPress += MyTreeView_KeyPress;
}
catch
{
}
}
//This is the code I added.
private void MyTreeView_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
Console.WriteLine("key_press_ok");
//error code↓
//textBox1.Text = "sample";
}
}
}
If you want just to click an button and then print some text i don't understand why you are making another class.
Will be good to make your code efficient and not complicated.
In the main class
private void SendText_Click(object sender, EventArgs e)
{
textBox1.Text = "hi";
}
But if you want to make it complicated and make a class you shuld return i variable and send it to the other class the you can use it.
Learn how to use Public and private first and then use them.
You shuld have a public class which send data and the private to recive and process.
add (Exception ex) to your try catch.
so do:
try
{
// your code
}
catch (Exception ex)
{
MessageBox.Show(ex, "Error in (add where the error is)");
Console.WriteLine(ex);
}
So you will get a detailed Exception Message, maybe it helps you or maybe you will post it here, so we can see what the problem is.
And because you have System.Windows.Forms in your Using Directive
using System.Windows.Forms;
so
System.Windows.Forms.TreeNode[] tree1 = new System.Windows.Forms.TreeNode[2];
is redundant and can be shortened to:
TreeNode[] tree1 = new TreeNode[2];

How do I make my DataGridView read info of a text file C#

so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present 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;
using System.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.

Entering data into Excel worksheets in an add in (C#)

I'm creating an add in for Microsoft Excel that includes a ribbon tab. On this tab is a button with the following code:
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
}
}
The button opens up a separate form where the user specifies budget_cell, account_cell, and transaction_cell. I then pass that data to the above code in SolutionName.ThisAddIn.cs (where SolutionName is the namespace of the solution). Strictly speaking, the code works. However, the data doesn't show up in the cells until the button is pressed a second time. Why is that? Is it because I'm retrieving the data from a different object in the solution?
Also, I've been trying to get this code and the aforementioned form to activate when the add in first starts up.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
I've been at this for a good twelve hours now, and I can't get it to work. What am I missing?
ThisAddIn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
namespace AccountingAddIn
{
public partial class ThisAddIn
{
public static string budget_cell = "";
public static string account_cell = "";
public static string transaction_cell = "";
public static string date_cell = "";
public static string time_cell = "";
public static string description_cell = "";
public static bool date = false;
public static bool time = false;
public static bool description = false;
public static decimal budget = 0;
List<Account> accounts = new List<Account>();
public void budgetStartUp()
{
frmStartup startup = new frmStartup();
startup.Show();
setAccounts();
}
public void setAccounts()
{
foreach (Excel.Worksheet displayWorksheet in Globals.ThisAddIn.Application.Worksheets)
{
displayWorksheet.Range[budget_cell].Value2 = "$" + Convert.ToString(budget);
displayWorksheet.Range[account_cell].Value2 = "$0.00";
displayWorksheet.Range[transaction_cell].Value2 = "Amount";
if (date == true)
{
displayWorksheet.Range[date_cell].Value2 = "Date";
}
if (time == true)
{
displayWorksheet.Range[time_cell].Value2 = "Time";
}
if (description == true)
{
displayWorksheet.Range[description_cell].Value2 = "Description";
}
Account na = new Account(0, displayWorksheet);
accounts.Add(na);
}
}
protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
return Globals.Factory.GetRibbonFactory().CreateRibbonManager(
new Microsoft.Office.Tools.Ribbon.IRibbonExtension[] { new MyRibbon() });
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
CreateRibbonExtensibilityObject();
budgetStartUp();
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
}
}
frmStartup.cs:
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 AccountingAddIn
{
public partial class frmStartup : Form
{
public frmStartup()
{
InitializeComponent();
}
private void btnHelp_Click(object sender, EventArgs e)
{
MessageBox.Show("Please enter a starting amount for your budget and " +
"which cells will display the running total for your " +
"accounts." +
"\n\nNote: Leaving the budget blank will" +
" result in a starting budget of $0.00.");
}
private void btnOkay_Click(object sender, EventArgs e)
{
AccountingSeminar.ThisAddIn.budget += Convert.ToDecimal(txtStartingAmount.Text);
AccountingSeminar.ThisAddIn.budget_cell = txtBudget.Text;
AccountingSeminar.ThisAddIn.account_cell = txtAccount.Text;
AccountingSeminar.ThisAddIn.transaction_cell = txtTransaction.Text;
if (chkDate.Checked)
{
AccountingSeminar.ThisAddIn.date_cell = txtDate.Text;
AccountingSeminar.ThisAddIn.date = true;
}
if (chkTime.Checked)
{
AccountingSeminar.ThisAddIn.time_cell = txtTime.Text;
AccountingSeminar.ThisAddIn.time = true;
}
if (chkDescription.Checked)
{
AccountingSeminar.ThisAddIn.description_cell = txtDescription.Text;
AccountingSeminar.ThisAddIn.description = true;
}
Close();
}
}
}

Waiting for event within a function

My goal:
User should be able to get the html source of a page, when clicked on a button. This event opens a new form with a geckoWebBrowser component and navigates to a given url.
Once this is done it fires a documentCompleted event.
Then I can start loading the DOM.
The problem:
While the loading of the page needs time, I have to wait untill in the second form class the DOM (or just the value of a div) is loaded. This is exactly the problem! Every wait or loop stucks the second form (geckoBrowser) so I can't get the value.
This is the code of the first form:
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;
using System.Threading;
namespace mozillaFirefox2
{
public partial class Form1 : Form
{
string source = "";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(bw_DoWork);
Browser br = new Browser();
//object parameters = br;
//bw.RunWorkerAsync(parameters);
br.navigate("http://www.google.com/#hl=en&q=superman&aq=f&aqi=&oq=&fp=1&cad=b");
Thread th = new Thread(delegate() { this.dw(br); });
th.Start();
th.Join(2000);
richTextBox1.AppendText(br.GetSource + "\n");
}
private void dw(Browser br)
{
while (br.workDone == false)
{
//donothing
}
source = br.GetSource;
}
//void bw_DoWork(object sender, DoWorkEventArgs e)
//{
// Browser br = (Browser)e.Argument;
// while (br.workDone == false)
// {
// //donothing
// }
// richTextBox1.AppendText(br.GetSource + "\n");
//}
}
}
This is the second:
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;
using System.Threading;
namespace mozillaFirefox2
{
//Declare a delegate who points to a function / signature
public delegate void GotDataEventHandler(object sender, EventArgs e);
class Browser : Form
{
public event GotDataEventHandler GotData;
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.geckoWebBrowser1 = new Skybound.Gecko.GeckoWebBrowser();
this.SuspendLayout();
//
// geckoWebBrowser1
//
this.geckoWebBrowser1.Location = new System.Drawing.Point(14, 4);
this.geckoWebBrowser1.Name = "geckoWebBrowser1";
this.geckoWebBrowser1.Size = new System.Drawing.Size(261, 67);
this.geckoWebBrowser1.TabIndex = 2;
this.geckoWebBrowser1.DocumentCompleted += new EventHandler(geckoWebBrowser1_DocumentCompleted);
//Never forget this. Otherwise this error is raised "Cannot call Navigate() before the window handle is created"
this.geckoWebBrowser1.CreateControl();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(788, 577);
this.Controls.Add(this.geckoWebBrowser1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
public Skybound.Gecko.GeckoWebBrowser geckoWebBrowser1;
public string source = "";
public bool workDone = false;
public bool navCall = false;
[STAThread]
public Browser()
{
Skybound.Gecko.Xpcom.Initialize(#"C:\Program Files\Mozilla-Gecko ActiveX WebBrowserControl\xulrunner-1.9.1.2.en-US.win32\xulrunner");
Skybound.Gecko.GeckoPreferences.User["general.useragent.override"] = "Mozilla/5.0 (Windows; U; Windows NT 6.0; nl; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)";
this.InitializeComponent();
this.Show();
}
public delegate void NavigationHandler(string url);
public void navigate(string url)
{
if (this.InvokeRequired)
{
object[] parameters = { url };
this.geckoWebBrowser1.Invoke(new NavigationHandler(navigate), parameters);
}
else
{
navCall = true;
this.geckoWebBrowser1.Navigate(url);
}
}
public string GetSource
{
get { return source; }
}
public string getSource()
{
return source;
}
public void geckoWebBrowser1_DocumentCompleted(object sender, EventArgs e)
{
if(navCall == true){
source = this.geckoWebBrowser1.Document.GetElementById("res").InnerHtml.ToString();
workDone = true;
navCall = false;
//
GotDataEventHandler gd;
lock (this)
{
gd = GotData;
}
if (gd != null)gd(this, EventArgs.Empty);
}
}
}
}
Now I should be able to just wait till I get an answer within the button1_Click function or catch the event within this function or a function on the second form so I can return this (than the code will wait by itself). Don't know how to do this.
The basic idea would be to split the function into two parts, putting the code that should be run after the event occurs in an anonymous delegate:
Instead of
void doStuff() {
firstPart();
waitEvent();
secondPart();
}
you do
void doStuff() {
firstPart();
some.Event += delegate {
secondPart();
}
}
The only alternative I know of is to put the whole processing into a second thread and use Monitor.Wait and Monitor.Pulse to tell the second thread when it may continue. This will create more overhead and will be generally slower, though. It might be a good idea, if you need to wait for 10 events and continue when the last one arrives (and you don't know the order), but not in that simple case you outline above.

Categories