Заполните comboBox в ленте Outlook данными из базы данных - PullRequest
0 голосов
/ 03 апреля 2019

Я создал ленту с кнопками для сохранения вложений Outlook на локальный диск, и она прекрасно работает. Теперь я хотел бы добавить comboBox на ленту, которая получает свои значения из базы данных MS SQL. Я не могу найти хороших примеров, описывающих, что именно мне нужно делать.

Я пытался использовать комбинированный список и меню, но все примеры, которые я встречал, всегда показывают ошибки программирования - VS.

Я пытался следовать этому руководству, но оно дает мне больше вопросов, чем ответов.

https://github.com/MicrosoftDocs/visualstudio-docs/blob/master/docs/vsto/walkthrough-updating-the-controls-on-a-ribbon-at-run-time.md

Это то, что я нашел до сих пор, но я думаю, что это для веб-форм или аналогичного программирования, но это не должно быть сложнее, чем это, или?

private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
    {
        string connetionString = null;
        SqlConnection connection;
        SqlCommand command;
        SqlDataAdapter adapter = new SqlDataAdapter();
        DataSet ds = new DataSet();
        int i = 0;
        string sql = null;
        connetionString = "Data Source=.;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
        sql = "select au_id,au_lname from authors";
        connection = new SqlConnection(connetionString);
        try
        {
            connection.Open();
            command = new SqlCommand(sql, connection);
            adapter.SelectCommand = command;
            adapter.Fill(ds);
            adapter.Dispose();
            command.Dispose();
            connection.Close();

            comboBox1.DataSource = ds.Tables[0];
            comboBox1.ValueMember = "au_id";
            comboBox1.DisplayMember = "au_lname";
        }
        catch (Exception ex)
        {
            MessageBox.Show("Can not open connection ! ");
        }
    }

Руководство, на которое я ссылался, дало мне это в коде, но в нем много ошибок кода. Я добавил все, используя требования, но безрезультатно.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Tools.Ribbon;
using Microsoft.Office.Interop.Outlook;
using System.IO;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Linq.Expressions;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace OutlookAddIn1
{


  public partial class Ribbon1
  {

    //<Snippet3>
    private RibbonDropDownItem CreateRibbonDropDownItem()
    {
        return this.Factory.CreateRibbonDropDownItem();
    }

    private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
    {
        //<Snippet2>
        //Declare the Northwind dataset.
        Ribbon_Update_At_Runtime.Northwind40DataSetTableAdapters.Northwind40DataSet nwDataSet = new Northwind40DataSet();

        //Declare the data tables.

        Northwind40DataSet.CustomersDataTable customerTable;
        Northwind40DataSet.OrdersDataTable orderTable;
        Northwind40DataSet.Order_DetailsDataTable orderDetailsTable;
        Northwind40DataSet.ProductsDataTable productsTable;

        //Declare the data table adapters for each table.

        CustomersTableAdapter customerTableAdapter = new CustomersTableAdapter();
        OrdersTableAdapter ordersTableAdapter = new OrdersTableAdapter();
        Order_DetailsTableAdapter detailsTableAdapter = new Order_DetailsTableAdapter();
        ProductsTableAdapter productsTableAdapter = new ProductsTableAdapter();
        //</Snippet2>


        customerTable = nwDataSet.Customers;
        customerTableAdapter.Fill(customerTable);

        var customerQuery = from customers in customerTable.AsEnumerable().Take(20)
                            select new
                            {
                                CustomerID = customers.Field<string>("Customer ID"),
                                CustomerName = customers.Field<string>("Contact Name")
                            };


        // Execute the query.
        foreach (var item in customerQuery)
        {
            this.comboBox1.Items.Add(CreateRibbonDropDownItem());
            this.comboBox1.Items.Last().Label = item.CustomerName + "|" + item.CustomerID.ToString();
        }
        this.comboBox1.Text = this.comboBox1.Items.First().Label;

    }
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...