使用按钮单击处理DataTable中添加的数据

时间:2017-04-26 12:16:48

标签: c# datagridview datatable

我正在寻找一种方法来处理我使用按钮点击在DataTable中添加的数据。 这是DataTable的代码

private DataTable ReadExcel(string fileName, string fileExt)
    {
        string conn = string.Empty;
        DataTable dtexcel = new DataTable();
        if (fileExt.CompareTo(".xls") == 0)
        {
            conn = @"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007  
        }
        else
            conn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=NO';"; //for above excel 2007  
        using (OleDbConnection con = new OleDbConnection(conn))
        {

            try
            {
                con.Open();
                OleDbDataAdapter oleAdpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", con); //here we read data from sheet1                           
                oleAdpt.Fill(dtexcel); //fill excel data into dataTable
                con.Dispose();
            }
            catch { }
        }
        return dtexcel;
    }

这就是按钮当前的工作方式:

private void loadFileButton_Click(object sender, EventArgs e)
    {
        string filePath = string.Empty;
        string fileExt = string.Empty;
        OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file  
        if (file.ShowDialog() == DialogResult.OK) //if there is a file choosen by the user  
        {
            filePath = file.FileName; //get the path of the file  
            fileExt = System.IO.Path.GetExtension(filePath); //get the file extension  
            loadFilePath.Text = filePath; //display the path to the file in the loadFile text box
            if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
            {
                try
                {                      
                    this.Cursor = Cursors.WaitCursor;
                    dataGridView1.VirtualMode = true;                       
                    dataGridView1.Visible = true;
                    dataGridView1.DataSource = ReadExcel(filePath, fileExt);                    
                    this.Cursor = Cursors.Default;
                    MessageBox.Show("File loaded successfully!", "Success!", MessageBoxButtons.OK); //custom message for successful file loading
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString());
                }
            }
            else
            {
                MessageBox.Show("Please choose .xls or .xlsx file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error  
            }
        }           
    }

程序和代码工作得很好,但问题在于DataTable()中已有的数据,而我似乎无法找到处理它的方法。在我的清除按钮中,我使用以下行this.dataGridView1.DataSource = null;,但这只清除已插入dataGridView的数据。请帮帮我。

提前谢谢。

0 个答案:

没有答案