01/10/2018, 09:27

Sửa lỗi trong C# winform

“Cannot perform runtime binding on a null reference”.

Mình gặp phải lỗi này khi import một file excel lên listview trong winform. Mình tạo đã tạo file excel bên ngoài, add reference cần thiết rồi. Mình mò mãi mà không fix được. Mọi người có thể giúp mình được không ạ. Cám ơn mọi người nhiều

Khanhvm viết 11:42 ngày 01/10/2018

Đưa source lên mọi người thử cho.

Đậu Nhỏ Hạt viết 11:32 ngày 01/10/2018

source đây ạ

//button Import
private void btnImport_Click(object sender, EventArgs e)
{
//Mở tệp tin
OpenFileDialog fopen = new OpenFileDialog();
//lọc ra đuôi excel
fopen.Filter = “(Tất cả các tệp)|.| (Các tệp excel)|*.xls”;
fopen.ShowDialog();

        //xử lý
        if (fopen.FileName != "")
        {
            lblPath.Text = fopen.FileName;

            //tạo đối tượng Excel
            Excel.Application app = new Excel.Application();
            //mở file excel, mở wordbook để chứa
            Excel.Workbook wb = app.Workbooks.Open(fopen.FileName);
            //đọc dữ liệu
            try
            {
                //mở sheet
                //muốn tham chiếu đến sheet nào thì ta lấy workbook của sheet đó
                Excel._Worksheet sheet = wb.Sheets[1]; // mảng sheet có chỉ số đầu là 1
                //tham chiếu tới toàn bộ  vùng dữ liệu
                Excel.Range range = sheet.UsedRange;
                //đọc dữ liệu
                int rows = range.Rows.Count;//lấy số dòng
                int cols = range.Rows.Count;//lấy số cột

                //đọc dòng tiêu đề để tạo cột cho listview
                for (int c = 1; c <= cols; c++)
                {
                    string columnName = range.Cells[1, c].value.ToString();//Cells[dòng, cột]
                    ColumnHeader col = new ColumnHeader();
                    //gán thuộc tính
                    col.Text = columnName;
                    col.Width = 120;
                    lsvSinhVien.Columns.Add(col);
                }


            }
            catch (Exception ex)
            {
                //thông báo lỗi
                MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OKCancel);
            }
        }
        else
        {
            MessageBox.Show("Bạn không chọn tệp tin nào", "Thông báo", MessageBoxButtons.OKCancel);
        }
    }
Bài liên quan
0