如何使用C#从Excel文件绑定ComboBox

时间:2011-07-26 19:43:49

标签: c# excel

我只想从myExcel.xls文件中的数据绑定一个Combobox。我的代码是:

  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.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            string strWB = @"\myExcel.xls";
            string strWBPath = @"C:\Users\Abid\Dropbox\Graphics\TEMP";

            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Open(strWBPath + strWB, 0, true, 5, "", "",
                true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            Excel.Range xlRange = xlWorkSheet.get_Range("A1", "A4");

            foreach (object item in xlRange)
            {
                comboBox1.Items.Add(item).ToString();
                comboBox1.Text = comboBox1.Items.Count.ToString();
                comboBox1.Text = comboBox1.Items.Add(item).ToString();
             //   listBox1.Items.Add(item).ToString();
            }
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }

            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object" + ex.ToString());
            }

            finally
            {
                GC.Collect();
            }

        }
    }
}

这不起作用...当我按Ctrl + F5并单击Button1时,组合框将与System .__ ComObject绑定..这是什么系统。 _CommObject?请帮帮我..

1 个答案:

答案 0 :(得分:0)

这样做

var item = ((Range)worksheet.Cells[rowIndex, columnIndex]).Value2.ToString()

然后将项目绑定到组合框

int start = 1;
int end = 10;
for(start; start < end; start++)
{
   var item = ((Range)xlWorkBook .Cells[rowIndex, columnIndex]).Value2.ToString();
  comboBox1.Items.Add(item);
}