简体   繁体   中英

Getting Null Reference error when trying to set a picture in Telerik Gridview

I'm trying to display pictures in a telerik gridview using the following bit of code:

  foreach (var item in radGridView1.Rows)
        {
            try
            {
                item.Cells["column1"].CellElement.Text = "";
                item.Cells["column1"].CellElement.StretchVertically = true;
                item.Cells["column1"].CellElement.ImageLayout = ImageLayout.Zoom;
                item.Cells["column1"].CellElement.ImageAlignment = ContentAlignment.MiddleCenter;
                item.Cells["column1"].CellElement.Image = Image.FromFile("img/1.jpg");
                pictureBox1.Image = Image.FromFile(item.Cells["Picture"].Value.ToString());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

But whenever i try to run the application , i get an error message complaining that the

Object reference not set to an instance of an object

What could be possibly wrong with it?!

Sounds like you're dereferencing a null object (eg null.SomeProperty ).

You should put a breakpoint on the line you're getting the error, and see which null object you're dereferencing.

Due to Telerik Virtualization in the controls such as RadGridView CellElements and RowElements can be null.So in order to format certain cells eg in a Telerik RadGridView control we need to use the "CellFormatting" event such as below:

 private void radGridView1_CellFormatting(object sender, CellFormattingEventArgs e)
        {
            try
            {
                if (e.CellElement.ColumnInfo.HeaderText == "Picture") 
                {
                    e.CellElement.Image = pictureBox1.Image;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

The same approach is valid for formatting certain rows using RowFormatting event of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM