Clearing DropDown List with Invalidate() Outlook Addin C# - c#

Ribbon1.cs using Ribbon Designer (ie, no XML)
I am trying to clear the contents of a Drop Down list before repopulating the list with new data.
I have tried using Invalidate() in several places but I can't get it to work.
The flow of the Addin is as followed:
Copy text to clipboard -> works
Click Search -> works
Get new Data from Database using text from Clipboard -> works
Clear Dropdown -> doesn't work
Populate Drop Down with data. -> Does work but add items to drop down instead of
clearing it first
Thanks in advance
using System;
using System.Collections.Generic;
using System.IO;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Office = Microsoft.Office.Core;
using Outlook = Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Tools.Ribbon;
namespace MSTEST
{
public partial class Ribbon1 : Office.IRibbonExtensibility
{
private Office.IRibbonUI ribbon;
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
this.ribbon = RibbonUI;
}
private void eventDB(object sender, RibbonControlEventArgs e)
{
RibbonUI.Invalidate();
//this.ribbon.InvalidateControl("resultsDB");
string getTextFromClipboard = Clipboard.GetText();
string queryString = "select distinct file_path as FP, case_id as CS, date_added from documents CONTAINS(documents.file_path, '" + getTextFromClipboard + "') group by case_id,file_path, datE_added order by Date_Added DESC";
using (OdbcConnection odbcConnection = new OdbcConnection("dsn=Needles;UID=dba;PWD=sql;"))
{
OdbcCommand command = new OdbcCommand(queryString, odbcConnection);
try
{
odbcConnection.Open();
OdbcDataReader reader = command.ExecuteReader();
// ribbon.InvalidateControl("resultsDB");
int i = 0;
while (reader.Read())
{
// Being DropDown Populate
RibbonDropDownItem item = this.Factory.CreateRibbonDropDownItem();
item.Label = reader["FP"].ToString();
resultsDB.Items.Add(item);
//MessageBox.Show(reader["CS"].ToString());
// End DropDown Populate
i = i + 1;
}
reader.Close();
odbcConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
public string GetCustomUI(string RibbonID)
{
throw new NotImplementedException();
}
}
}

I have solved this by tinkering around with the Clear() function of the object. example: resultsDB.Items.Clear();

Related

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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 System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

c# importing excel to datagridview doesn't work

I am using ExcelDataReader here.
I don't know why below code doesn't work.
It doesn't generate any error but it still doesn't show excel data.
It simply doesn't do anything after loading excel file.
I am new to C# and after 5 hours of digging I feel frustrated since I don't know why this doesn't work.
using Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class ExcelForm : Form
{
public ExcelForm()
{
InitializeComponent();
}
private void ExcelForm_Load(object sender, EventArgs e)
{
}
DataSet result;
private void btnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel(.xls)|*.xls|Excel(.xlsx)|*.xlsx", ValidateNames = true })
{
if(ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader;
if (ofd.FilterIndex == 1)
reader = ExcelReaderFactory.CreateBinaryReader(fs);
else
reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
reader.Close();
dataGridView.DataSource = result;
}
}
}
}
}
dataGridView.DataSource = DtSet.Tables[0];

keep having this exception System.Data.OleDb.OleDbException (0x80004005):?

i am developping a really simple program in c# with Visual studio, it consists simply by extracting data from an Excel sheet and transfer it to a database (only one table ), using MySql it worked i just saved the files as CSV and then imported them into my database but i had a big problem which was the encoding UTF8 i have many french characters ans arabic ones that just showed as random characters, so i went back to OleDb but it keeps shong exceptions now i am stuck with this one: System.Data.OleDb.OleDbException (0x80004005)
i ve tried to change running config to x86 but nothing (notice that i am using a windows 8 X64). its a cummon ISAM problem.
please help me .
this is my 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 Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
using System.Data.OleDb;
namespace testoledb
{
public partial class Form1 : Form
{
DataSet OleDs = new DataSet();
OleDbDataAdapter OleAdapter = new OleDbDataAdapter();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void upload_excl_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
path = Path.Combine(path, "AGENDA.xlsx");
string OleConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+path+#";Extend Properties=Excel 12.0 Macro;MDR=Yes;ImportMixedTypes=Text;TypeGuessRows=0"; //,HDR=Yes;IMEX=1""";
OleDbConnection OleConn = new OleDbConnection(OleConnectionString);
string OleStrCmd = "select * from [SHeet1$A1:H330]";
OleDbCommand OleCmd = new OleDbCommand(OleStrCmd, OleConn);
try
{
OleConn.Open();
OleDs.Clear();
OleAdapter.SelectCommand = OleCmd;
OleAdapter.Fill(OleDs);
dataGridView1.DataSource = OleDs.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
OleConn.Close();
}
}
}
}

IMAP searchParse exception?

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.Web;
using ActiveUp.Net.Mail;
using ActiveUp.Net.Imap4;
namespace imapClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Imap4Client client = new Imap4Client();
client.ConnectSsl("imap.gmail.com", 993);
MessageBox.Show("connected!");
client.Login("soham.elf", "********");
MessageBox.Show("signed in!");
Mailbox mail = client.SelectMailbox("INBOX");
//exception thrown here
MessageCollection msgs = mail.SearchParse("ALL");
textBox1.Text = msgs.Count.ToString();
}
}
}
Expection:"Index and length must refer to a location within the string.
Parameter name: length"
I am trying to test the IMAP client; I'm just starting with it. I am using mailsystem.NET. What's wrong with my code?
Try use Phrases like that document: http://www.limilabs.com/blog/imap-search-requires-parentheses
private void SearchFromTest()
{
try
{
var _selectedMailBox = "INBOX";
var _searchWithEmailFrom = "email#domain.com";
using (var _clientImap4 = new Imap4Client())
{
_clientImap4.ConnectSsl(_imapServerAddress, _imapPort);
//_clientImap4.Connect(_mailServer.address, _mailServer.port);
_clientImap4.Login(_imapLogin, _imapPassword); // Efetua login e carrega as MailBox da conta.
//_clientImap4.LoginFast(_imapLogin, _imapPassword); // Efetua login e não carrega as MailBox da conta.
var _mailBox = _clientImap4.SelectMailbox(_selectedMailBox);
// A0001 SEARCH CHARSET utf-8 BODY "somestring" OR TO "someone#me.com" FROM "someone#me.com"
var searchPhrase = "CHARSET utf-8 FROM \"" + _searchWithEmailFrom + "\"";
foreach (var messageId in _mailBox.Search(searchPhrase).AsEnumerable())
{
var message = _mailBox.Fetch.Message(messageId);
var _imapMessage = Parser.ParseMessage(message);
}
_clientImap4.Disconnect();
}
Assert.IsTrue(true);
}
catch (Exception e)
{
Assert.Fail("Don't work.", e);
}
}

how do I turn this into a custom excel function?

I have the following C# code, which pulls data from a database & populates cell A1 w/ the data when Excel loads. How do I turn this into a custom function, whereby the field would populate when the user types in the formula (ie '=getMyData("mycustominput")'), rather than when excel loads?
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;
using MySql.Data.MySqlClient;
namespace custom_excel
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
Excel.Range firstRow = activeWorksheet.get_Range("A1", missing);
firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, System.Type.Missing);
Excel.Range newFirstRow = activeWorksheet.get_Range("A1", missing);
string connString = "Server=localhost;Port=3306;Database=test;Uid=name;password=password";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT field_value FROM customers LIMIT 1";
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
newFirstRow.Value2 = reader["field_value"].ToString();
}
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
}
}
Going out on a limb here, but have you looked at ExcelDNA? It sounds like it might work for what you are trying to do.
There is also this somewhat older article from Eric Carter that might be of use, which uses an automation add-in. It appears you can do it without any 3rd party libraries.

Categories

Resources