数据未在datagridview中显示

时间:2011-08-09 10:31:52

标签: winforms

我目前正在将数据从excel表导入到sql server.i编写了一个代码,用于从excel表中删除空行..现在我试图通过将方法名称分配给datagridview来查看datagridview中的数据datasource..but它没有显示任何数据。如果我做的正确或错误,任何人都可以说我。这是我的代码..

   public partial class Form9 : Form
{
    DataSet dsExcel = new DataSet();

    public Form9()
    {
        InitializeComponent();
    }

    private void btnUpload_Click(object sender, EventArgs e)
    {
        //String input = string.Empty;
        OpenFileDialog filepath = new OpenFileDialog();
        filepath.Filter = "Excel Files(*.xls)|*.xls|Excel Files(*.xlsx)|*.xlsx|Text Files(*.txt)|*.txt|All Files(*.*)|*.*";
        filepath.InitialDirectory = "C:";
        filepath.Title = "Select a file";
        if (filepath.ShowDialog() == DialogResult.OK)
            txtExcelFile.Text = filepath.FileName;
        if (txtExcelFile.Text == string.Empty)
            return;
    }

    private void btnImport_Click(object sender, EventArgs e)
    {


        OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + txtExcelFile.Text + "';Extended Properties= 'Excel 8.0;HDR=Yes;IMEX=1'");
        cnn.Open();
        try
        {

            OleDbDataAdapter data = new OleDbDataAdapter("select * from [Customers$]", cnn);

            data.Fill(dsExcel);

            dgvCustomers.ColumnHeadersVisible = false;
            dgvCustomers.DataSource = GetExcelData();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            //cnn.Close();
        }

    }

       public DataSet GetExcelData()
        {
        DataTable ExcelTable = new DataTable();
        List<int> rowToRemove = new List<int>();
        //DataRow ExcelRow = new DataRow();

        foreach (DataRow excelrow in dsExcel.Tables[0].Rows)
        {
            bool IsEmpty = false;
            foreach (object item in excelrow.ItemArray)
            {
                if (String.IsNullOrEmpty(item.ToString())) 
                {
                     IsEmpty = true;
                     break;

                }                  
                else
                {
                    IsEmpty = false;

                }
            }
            if (IsEmpty)
            { 
                rowToRemove.Add((dsExcel.Tables[0].Rows.IndexOf(excelrow)));
            }

        }

        for (int i = rowToRemove.Count - 1; i >= 0; i--)
        {
            dsExcel.Tables[0].Rows.RemoveAt(rowToRemove[i]);

        }
        return dsExcel;

    }
}

}

1 个答案:

答案 0 :(得分:0)

您的数据源应该是数据集中的数据表,而不是数据集本身。

更改

public DataSet GetExcelData()

public DataTable GetExcelData()

最后,请回复:

return dsExcel.Tables[0];