使用excel表C#中的列填充组合框

时间:2017-02-21 05:47:41

标签: c# excel combobox

System.Data.DataRowView仅显示在组合框中,而不是Project.xlsx的Sheet1中的“pmName”。此外,添加DisplayMember或ValueMember表示属性不存在时会出现错误。

public void LoadCustomerCombo3()
{
 try
 {
   using (OleDbConnection conn = new OleDbConnection(constr_xls))
   {
     conn.Open();
     string strSql = "SELECT pmName FROM [Sheet1$]"; 
     OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(strSql, conn));
     DataSet ds = new DataSet();
     adapter.Fill(ds);
     testCombo.ItemsSource = ds.Tables[0].DefaultView;
     conn.Close();
   }
  }
  catch (Exception ex)
  {
     Console.WriteLine(ex.Message);
  }
 }

2 个答案:

答案 0 :(得分:0)

尝试逐个添加项目 foreach (var item in xlRange) { comboBox1.Items.Add(item); }

答案 1 :(得分:0)

        try
        {
            OleDbConnection conn = new OleDbConnection();
            conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\kanndeva\\Documents\\Visual Studio 2015\\Projects\\DVC_ProjTool\\Project.xlsx; Extended Properties=Excel 12.0 XML;";
            conn.Open();
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn);
            DataTable ds = new DataTable();
            da.Fill(ds);
            stdCombo.Text = "--Select--";
            for (int i = 0; i < ds.Rows.Count; i++)
            {
                stdCombo.Items.Add(ds.Rows[i]["pmName"]);
            }

            conn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.GetBaseException().ToString(), "Error In Connection");
        }

这个工作!谢谢@AKN