2
votes

I have prepared a simple code for reading excel file to c# Wpf form.

But i am getting error:

{"Cannot perform runtime binding on a null reference"}.

Below is code....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication9
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("Book1.xlsx");
            Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            for (int i = 1; i <= rowCount; i++)
            {
                for (int j = 1; j<= colCount; j++)
                {
                    MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
                }
            }
        }
    }
}
1
Check your front end code for typographical errors. - Paul Zahra
The error looks like a XAML binding error that has nothing to do with Excel. Do you get any exceptions in the code you posted? Where does that message come from? Where is your XAML and where do you use binding? - Panagiotis Kanavos
It is a little bit easier on the eyes than NullReferenceException. Tells you that a dynamic object is null. It otherwise means the exact same thing. You cannot blindly assume that every cell has a value. - Hans Passant

1 Answers

0
votes

Don't use .ToString() method. It will cause null reference exception when the value is null.

Use can use Convert.ToString()