写一个WinForm程序,需要点击按钮之后将一个xls文件导入到dataGridView里显示出来
看了很多朋友的代码,和自己写的是一样的,但在我这里无法正常工作。代码我检查过很多次,是按照标准格式写的。
触发事件之后dataGridView里没有显示任何东西(等于没有导入),同时也没有任何抛出任何异常
麻烦高手们帮忙看看,感谢private void button1_Click(object sender, EventArgs e)
{
     try
     {
      OleDbConnection oledbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\1.xls;Extended Properties='Excel 8.0;HDR=No;IMEX=1'");
      oledbcon.Open();
      string xlsstr = "select * from [Sheet1$]";
      OleDbDataAdapter myda = new OleDbDataAdapter(xlsstr, oledbcon);
      DataSet myds = new DataSet();
      myda.Fill(myds);
      this.dataGridView1.DataSource = myds;
      oledbcon.Close(); 
      }
      catch
      {
           MessageBox.Show("读取文件错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
}

解决方案 »

  1.   

    myds是一个Dataset,你必须指定DataGridView.ValueMember为一个DataTable的Name,你直接给this.dataGridView1.DataSource设置了一个DataSet,肯定不会显示,因为DataGridView期望显示一个DataTable.
      

  2.   

    写的有些问题,应该是:
    myds是一个DataSet,除了设置DataSource,你还必须指定DataGridView.DataMember为一个DataTable的Name,你直接给 this.dataGridView1.DataSource设置了一个DataSet,肯定不会显示,因为DataGridView期望显示一个 DataTable.
    如果myds是一个DataTable就没有问题,直接设置给DataSource属性。
      

  3.   

    string fileName = null;
        this.OpenFileDialog1.Filter = "Excle文件(*.xls)|*.xls";
        if (this.OpenFileDialog1.ShowDialog() == DialogResult.OK) {
            fileName = this.OpenFileDialog1.FileName;
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + fileName + "';Extended Properties=Excel 8.0;";
            DataSet myDataset = new DataSet();
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
            try {
                da.Fill(myDataset);
                this.DataGrid1.DataSource = myDataset.Tables[0];
            }
            catch (Exception ex) {
                MessageBox.Show("读取文件错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
      

  4.   

    private void button1_Click(object sender, EventArgs e)
    {
      try
      {
      OleDbConnection oledbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\1.xls;Extended Properties='Excel 8.0;HDR=No;IMEX=1'");
      oledbcon.Open();
      string xlsstr = "select * from [Sheet1$]";
      OleDbDataAdapter myda = new OleDbDataAdapter(xlsstr, oledbcon);
      DataSet myds = new DataSet();
      myda.Fill(myds);
      this.dataGridView1.DataSource = myds.Tables[0];//绑定datatable
      oledbcon.Close();  
      }
      catch (Exception ex)
      {
      MessageBox.Show("读取文件错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }