System windows forms datagridviewcell value get вернул null

Реализация DI в PHP

Jason-Webb 13.05.2025

Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .

Обработка изображений в реальном времени на C# с OpenCV

stackOverflow 13.05.2025

Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .

POCO, ACE, Loki и другие продвинутые C++ библиотеки

NullReferenced 13.05.2025

В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .

Паттерны проектирования GoF на C#

UnmanagedCoder 13.05.2025

Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .

Создаем CLI приложение на Python с Prompt Toolkit

py-thonny 13.05.2025

Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .

Конвейеры ETL с Apache Airflow и Python

AI_Generated 13.05.2025

ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .

Выполнение асинхронных задач в Python с asyncio

py-thonny 12.05.2025

Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .

Работа с gRPC сервисами на C#

UnmanagedCoder 12.05.2025

gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .

CQRS (Command Query Responsibility Segregation) на Java

Javaican 12.05.2025

CQRS — Command Query Responsibility Segregation, или разделение ответственности команд и запросов. Суть этого архитектурного паттерна проста: операции чтения данных (запросы) отделяются от операций. . .

Шаблоны и приёмы реализации DDD на C#

stackOverflow 12.05.2025

Когда я впервые погрузился в мир Domain-Driven Design, мне показалось, что это очередная модная методология, которая скоро канет в лету. Однако годы практики убедили меня в обратном. DDD — не просто. . .

Hello i have simple problem
If no values in datagrid need to repair my code

Error is:

System.NullReferenceException: ‘Object reference not set to an instance of an object.’ System.Windows.Forms.DataGridViewCell.Value.get returned null.

My code

private void ListDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    foreach (DataGridViewRow row in ListDataGridView.Rows)
    {
        if (String.IsNullOrWhiteSpace(row.Cells["R.b."].Value.ToString()))
        {
            row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#51B3E8");
        }
        else
        {
            row.DefaultCellStyle.ForeColor = System.Drawing.ColorTranslator.FromHtml("#09ECA6");
        }
    }
}

Answers (2)

Example 1: System.Windows.Forms.DataGridView.CurrentRow.get returned null. c#

if(datagridview1[1, dataGridView1.CurrentRow.Index].Value == null)
{
    return;
}

Example 2: System.Windows.Forms.DataGridView.CurrentRow.get returned null. c#

if(dataGridView1.CurrentRow == null)
{
    return;
}

Tags:

Csharp Example

Related

September 18, 2022
PHP
  • Current row returns null in datagridview c
  • System.Windows.Forms.DataGridView.CurrentRow.get returned null. c
  • System.Windows.Forms.DataGridView.CurrentRow.get returned null. c# code
  • System.Windows.Forms.DataGridView.CurrentRow.get returned null. c
  • How Can Fixed This Erorr (System.Windows.Forms.DataGridViewCell.Value.get
  • System.Windows.Forms.DataGridView.CurrentRow.get returned null. c
  • DataGridView Class
  • System.NullReferenceException datagridview object reference not set to an

Current row returns null in datagridview c

Thanks for the pointing about Hide () Due to visible false (dgSuggest.Columns
[0].Visible = false;) to the first column of the grid you are facing the
problem of the current row is null. Set the first column of data grid view to
visible true (dgSuggest.Columns [0].Visible = true;)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace App
{
    public static class General
    {
        private static BindingSource source;
        private static bool typing = false;
        private static DataGridView dgSuggest;
        public static int productID;
        private static ComponentFactory.Krypton.Toolkit.KryptonTextBox txtBox;
        /// <summary>
        /// To show the auto suggest 
        /// </summary>
        /// <param name="parent">Windows.Form</param>
        /// <param name="tBox">krypton TextBox</param>
        /// <param name="dataSource">Datasource for the Suggestion</param>
        /// <param name="indexes">Indexes to hide in suggestion</param>
        public static void autoSuggest(Form parent,ComponentFactory.Krypton.Toolkit.KryptonTextBox tBox,BindingSource dataSource,int[] indexes)
        {
            source = dataSource;
            txtBox = tBox;
            dgSuggest = new DataGridView();
            parent.Controls.Add(dgSuggest);
            dgSuggest.BringToFront();
            dgSuggest.AllowUserToAddRows = false;
            dgSuggest.AllowUserToDeleteRows = false;
            dgSuggest.Location = new System.Drawing.Point(txtBox.Location.X,txtBox.Location.Y + txtBox.Height);
            dgSuggest.Width = txtBox.Width;
            dgSuggest.ReadOnly = true;
            dgSuggest.RowHeadersVisible = false;
            dgSuggest.DataSource = source;
            dgSuggest.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            dgSuggest.Columns[0].Visible = false;
            dgSuggest.Columns[2].Visible = false;
            dgSuggest.Columns[3].Visible = false;
            dgSuggest.Columns[4].Visible = false;
            dgSuggest.Columns[5].Visible = false;
            dgSuggest.Columns[6].Visible = false;
            dgSuggest.Columns[7].Visible = false;
            dgSuggest.Columns[8].Visible = false;
            dgSuggest.Columns[9].Visible = false;

            dgSuggest.Hide();
            dgSuggest.Columns[1].Width = txtBox.Width - 20;
            txtBox.KeyDown += new KeyEventHandler(txtBox_KeyDown);
            txtBox.KeyPress += new KeyPressEventHandler(txtBox_KeyPress);
            txtBox.TextChanged += new EventHandler(txtBox_TextChanged);
        }

        private static void txtBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (dgSuggest.Visible == false)
            {
                dgSuggest.Visible = true;
            }

            if (e.KeyCode == Keys.Down)
            {
                int rowIndex = 0;
                if (dgSuggest.Rows.Count > 0)
                {
                    if (dgSuggest.CurrentRow.Index < dgSuggest.Rows.Count - 1)
                    {
                        rowIndex = dgSuggest.CurrentRow.Index + 1;
                    }

                    dgSuggest.ClearSelection();
                    dgSuggest.CurrentCell = dgSuggest.Rows[rowIndex].Cells[1];
                    dgSuggest.Rows[rowIndex].Selected = true;
                }
            }
            else if (e.KeyCode == Keys.Up)
            {
                int rowIndex = 0;
                if (dgSuggest.Rows.Count > 0)
                {
                    if (dgSuggest.CurrentRow.Index > 0)
                    {
                        rowIndex = dgSuggest.CurrentRow.Index - 1;
                    }
                    else
                    {
                        rowIndex = dgSuggest.Rows.Count - 1;
                    }

                    dgSuggest.ClearSelection();
                    dgSuggest.CurrentCell = dgSuggest.Rows[rowIndex].Cells[1];
                    dgSuggest.Rows[rowIndex].Selected = true;
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                DataGridViewRow row = dgSuggest.CurrentRow;
                productID = Convert.ToInt32(row.Cells[0].Value);
                txtBox.Text = Convert.ToString(row.Cells[1].Value);
                dgSuggest.Hide();
            }
            else if (e.KeyCode == Keys.Back)
            {
                if (txtBox.Text != "")
                {
                    txtBox.Text = txtBox.Text.Substring(0, txtBox.Text.Length - 1);
                }
            }
            else if (e.KeyCode == Keys.Delete)
            {
                txtBox.Text = "";
            }

            e.Handled = true;
        }


        private static void txtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (char.IsControl(e.KeyChar) == false)
            {
                txtBox.Text = txtBox.Text + Convert.ToString(e.KeyChar);
                typing = true;
            }

            if(e.KeyChar == Convert.ToChar(Keys.Back))
            {
                typing = true;
            }
            e.Handled = true;
        }

        private static void txtBox_TextChanged(object sender, EventArgs e)
        {
            if (typing)
            {
                if (txtBox.Text == "")
                {
                    source.Filter = "";
                }
                else
                {
                    MessageBox.Show(source.Filter);
                    source.Filter = "Name LIKE '"+txtBox.Text+"%'";
                }
            }
            txtBox.SelectionStart = 0;
            txtBox.SelectionLength = txtBox.Text.Length;
        }
    }
}



BindingSource source = new BindingSource();
source.DataSource = ies.tblProducts;
General.autoSuggest(this, txtProduct,source,new int[]{0});



if (dgSuggest.CurrentRow != null &&
    dgSuggest.CurrentRow.Index < dgSuggest.Rows.Count - 1)
{
    rowIndex = dgSuggest.CurrentRow.Index + 1;
}

System.Windows.Forms.DataGridView.CurrentRow.get returned null. c

The solution for ” System.Windows.Forms.DataGridView.CurrentRow.get returned
null. c# ” can be found here. The following code will assist you in solving
the problem.

if(datagridview1[1, dataGridView1.CurrentRow.Index].Value == null)
{
    return;
}

System.Windows.Forms.DataGridView.CurrentRow.get returned null. c# code

example

System.Windows.Forms.DataGridView.CurrentRow.get returned null. c# code
example

if(datagridview1[1, dataGridView1.CurrentRow.Index].Value == null)
{
    return;
}


if(dataGridView1.CurrentRow == null)

{
    return;
}


if(dataGridView1.CurrentRow == null)
{
    return;
}

System.Windows.Forms.DataGridView.CurrentRow.get returned null. c

Level up your programming skills with exercises across 52 languages, and
insightful discussion with our dedicated team of welcoming mentors.

if(dataGridView1.CurrentRow == null)

{
    return;
}



                                    if(dataGridView1.CurrentRow == null)
{
&nbsp; &nbsp; return;
}


                                    if(datagridview1[1, dataGridView1.CurrentRow.Index].Value == null)
{
&nbsp; &nbsp; return;
}

How Can Fixed This Erorr (System.Windows.Forms.DataGridViewCell.Value.get

returned null. )

Depends on what you want to happen in case the cell value is null. The easiest
way to deal with it would be using the ? operator like this: txtCode.Text =
dgvIncome.SelectedRows[0].Cells[1].Value?.ToString(); This would assign null
to to the Text property of the textboxes in case the cell value is null which
is probably what you’d want.

        private void DgvIncome_MouseClick(object sender, MouseEventArgs e)
        {

            //try
            {
                txtCode.Text = dgvIncome.SelectedRows[0].Cells[1].Value.ToString();
                txtRecNo.Text = dgvIncome.SelectedRows[0].Cells[2].Value.ToString();
                txtMembershipID.Text = dgvIncome.SelectedRows[0].Cells[3].Value.ToString();
                txtGustName.Text = dgvIncome.SelectedRows[0].Cells[4].Value.ToString();
                txtGustMobile.Text = dgvIncome.SelectedRows[0].Cells[5].Value.ToString();
                txtNote.Text = dgvIncome.SelectedRows[0].Cells[6].Value.ToString();
                txtSalesNo.Text = dgvIncome.SelectedRows[0].Cells[7].Value.ToString();
                txtMainPackageNo.Text = dgvIncome.SelectedRows[0].Cells[8].Value.ToString();
                txtSubPackageNo.Text = dgvIncome.SelectedRows[0].Cells[9].Value.ToString();
                txtPackageNo.Text = dgvIncome.SelectedRows[0].Cells[10].Value.ToString();
                txtNatPrice.Text = dgvIncome.SelectedRows[0].Cells[11].Value.ToString();
                txtDiscount.Text = dgvIncome.SelectedRows[0].Cells[12].Value.ToString();
                dtpStartDate.Text = dgvIncome.SelectedRows[0].Cells[13].Value.ToString();
                dtpEndDate.Text = dgvIncome.SelectedRows[0].Cells[14].Value.ToString();
                ShowSalesName();
                ShowMainPackageName();
                ShowSubPackageName();
                ShowPackageName();
                ShowPrice();
                chbxSearch.Checked = false;
            }




System.NullReferenceException: 'Object reference not set to an instance of an object.'

System.Windows.Forms.DataGridViewCell.Value.get returned null.



txtCode.Text = dgvIncome.SelectedRows[0].Cells[1].Value?.ToString();

System.Windows.Forms.DataGridView.CurrentRow.get returned null. c

Get code examples like»System.Windows.Forms.DataGridView.CurrentRow.get
returned null. c#». Write more code and save time using our ready-made code
examples.

if(dataGridView1.CurrentRow == null)
{
    return;
}


if(dataGridView1.CurrentRow == null)

{
    return;
}



if(datagridview1[1, dataGridView1.CurrentRow.Index].Value == null)
{
    return;
}

DataGridView Class

The DataGridView class allows customization of cells, rows, columns, and
borders through the use of properties such as DefaultCellStyle,
ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor. For more
information, see Basic Formatting and Styling in the Windows Forms
DataGridView Control. You can use a DataGridView control to display

public ref class DataGridView : System::Windows::Forms::Control, System::ComponentModel::ISupportInitialize


[System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")]
[System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.Windows.Forms.Docking(System.Windows.Forms.DockingBehavior.Ask)]
public class DataGridView : System.Windows.Forms.Control, System.ComponentModel.ISupportInitialize


[System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")]
[System.Windows.Forms.Docking(System.Windows.Forms.DockingBehavior.Ask)]
public class DataGridView : System.Windows.Forms.Control, System.ComponentModel.ISupportInitialize


[<System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")>]
[<System.Runtime.InteropServices.ClassInterface(System.Runtime.InteropServices.ClassInterfaceType.AutoDispatch)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
[<System.Windows.Forms.Docking(System.Windows.Forms.DockingBehavior.Ask)>]
type DataGridView = class
    inherit Control
    interface ISupportInitialize


[<System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")>]
[<System.Windows.Forms.Docking(System.Windows.Forms.DockingBehavior.Ask)>]
type DataGridView = class
    inherit Control
    interface ISupportInitialize


Public Class DataGridView
Inherits Control
Implements ISupportInitialize


using System;
using System.Drawing;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
    private Panel buttonPanel = new Panel();
    private DataGridView songsDataGridView = new DataGridView();
    private Button addNewRowButton = new Button();
    private Button deleteRowButton = new Button();

    public Form1()
    {
        this.Load += new EventHandler(Form1_Load);
    }

    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        SetupLayout();
        SetupDataGridView();
        PopulateDataGridView();
    }

    private void songsDataGridView_CellFormatting(object sender,
        System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
    {
        if (e != null)
        {
            if (this.songsDataGridView.Columns[e.ColumnIndex].Name == "Release Date")
            {
                if (e.Value != null)
                {
                    try
                    {
                        e.Value = DateTime.Parse(e.Value.ToString())
                            .ToLongDateString();
                        e.FormattingApplied = true;
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("{0} is not a valid date.", e.Value.ToString());
                    }
                }
            }
        }
    }

    private void addNewRowButton_Click(object sender, EventArgs e)
    {
        this.songsDataGridView.Rows.Add();
    }

    private void deleteRowButton_Click(object sender, EventArgs e)
    {
        if (this.songsDataGridView.SelectedRows.Count > 0 &&
            this.songsDataGridView.SelectedRows[0].Index !=
            this.songsDataGridView.Rows.Count - 1)
        {
            this.songsDataGridView.Rows.RemoveAt(
                this.songsDataGridView.SelectedRows[0].Index);
        }
    }

    private void SetupLayout()
    {
        this.Size = new Size(600, 500);

        addNewRowButton.Text = "Add Row";
        addNewRowButton.Location = new Point(10, 10);
        addNewRowButton.Click += new EventHandler(addNewRowButton_Click);

        deleteRowButton.Text = "Delete Row";
        deleteRowButton.Location = new Point(100, 10);
        deleteRowButton.Click += new EventHandler(deleteRowButton_Click);

        buttonPanel.Controls.Add(addNewRowButton);
        buttonPanel.Controls.Add(deleteRowButton);
        buttonPanel.Height = 50;
        buttonPanel.Dock = DockStyle.Bottom;

        this.Controls.Add(this.buttonPanel);
    }

    private void SetupDataGridView()
    {
        this.Controls.Add(songsDataGridView);

        songsDataGridView.ColumnCount = 5;

        songsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
        songsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
        songsDataGridView.ColumnHeadersDefaultCellStyle.Font =
            new Font(songsDataGridView.Font, FontStyle.Bold);

        songsDataGridView.Name = "songsDataGridView";
        songsDataGridView.Location = new Point(8, 8);
        songsDataGridView.Size = new Size(500, 250);
        songsDataGridView.AutoSizeRowsMode =
            DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
        songsDataGridView.ColumnHeadersBorderStyle =
            DataGridViewHeaderBorderStyle.Single;
        songsDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
        songsDataGridView.GridColor = Color.Black;
        songsDataGridView.RowHeadersVisible = false;

        songsDataGridView.Columns[0].Name = "Release Date";
        songsDataGridView.Columns[1].Name = "Track";
        songsDataGridView.Columns[2].Name = "Title";
        songsDataGridView.Columns[3].Name = "Artist";
        songsDataGridView.Columns[4].Name = "Album";
        songsDataGridView.Columns[4].DefaultCellStyle.Font =
            new Font(songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic);

        songsDataGridView.SelectionMode =
            DataGridViewSelectionMode.FullRowSelect;
        songsDataGridView.MultiSelect = false;
        songsDataGridView.Dock = DockStyle.Fill;

        songsDataGridView.CellFormatting += new
            DataGridViewCellFormattingEventHandler(
            songsDataGridView_CellFormatting);
    }

    private void PopulateDataGridView()
    {

        string[] row0 = { "11/22/1968", "29", "Revolution 9", 
            "Beatles", "The Beatles [White Album]" };
        string[] row1 = { "1960", "6", "Fools Rush In", 
            "Frank Sinatra", "Nice 'N' Easy" };
        string[] row2 = { "11/11/1971", "1", "One of These Days", 
            "Pink Floyd", "Meddle" };
        string[] row3 = { "1988", "7", "Where Is My Mind?", 
            "Pixies", "Surfer Rosa" };
        string[] row4 = { "5/1981", "9", "Can't Find My Mind", 
            "Cramps", "Psychedelic Jungle" };
        string[] row5 = { "6/10/2003", "13", 
            "Scatterbrain. (As Dead As Leaves.)", 
            "Radiohead", "Hail to the Thief" };
        string[] row6 = { "6/30/1992", "3", "Dress", "P J Harvey", "Dry" };

        songsDataGridView.Rows.Add(row0);
        songsDataGridView.Rows.Add(row1);
        songsDataGridView.Rows.Add(row2);
        songsDataGridView.Rows.Add(row3);
        songsDataGridView.Rows.Add(row4);
        songsDataGridView.Rows.Add(row5);
        songsDataGridView.Rows.Add(row6);

        songsDataGridView.Columns[0].DisplayIndex = 3;
        songsDataGridView.Columns[1].DisplayIndex = 4;
        songsDataGridView.Columns[2].DisplayIndex = 0;
        songsDataGridView.Columns[3].DisplayIndex = 1;
        songsDataGridView.Columns[4].DisplayIndex = 2;
    }


    [STAThreadAttribute()]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    }
}



Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    Private buttonPanel As New Panel
    Private WithEvents songsDataGridView As New DataGridView
    Private WithEvents addNewRowButton As New Button
    Private WithEvents deleteRowButton As New Button

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        SetupLayout()
        SetupDataGridView()
        PopulateDataGridView()

    End Sub

    Private Sub songsDataGridView_CellFormatting(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
        Handles songsDataGridView.CellFormatting

        If e IsNot Nothing Then

            If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
            "Release Date" Then
                If e.Value IsNot Nothing Then
                    Try
                        e.Value = DateTime.Parse(e.Value.ToString()) _
                            .ToLongDateString()
                        e.FormattingApplied = True
                    Catch ex As FormatException
                        Console.WriteLine("{0} is not a valid date.", e.Value.ToString())
                    End Try
                End If
            End If

        End If

    End Sub

    Private Sub addNewRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles addNewRowButton.Click

        Me.songsDataGridView.Rows.Add()

    End Sub

    Private Sub deleteRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles deleteRowButton.Click

        If Me.songsDataGridView.SelectedRows.Count > 0 AndAlso _
            Not Me.songsDataGridView.SelectedRows(0).Index = _
            Me.songsDataGridView.Rows.Count - 1 Then

            Me.songsDataGridView.Rows.RemoveAt( _
                Me.songsDataGridView.SelectedRows(0).Index)

        End If

    End Sub

    Private Sub SetupLayout()

        Me.Size = New Size(600, 500)

        With addNewRowButton
            .Text = "Add Row"
            .Location = New Point(10, 10)
        End With

        With deleteRowButton
            .Text = "Delete Row"
            .Location = New Point(100, 10)
        End With

        With buttonPanel
            .Controls.Add(addNewRowButton)
            .Controls.Add(deleteRowButton)
            .Height = 50
            .Dock = DockStyle.Bottom
        End With

        Me.Controls.Add(Me.buttonPanel)

    End Sub

    Private Sub SetupDataGridView()

        Me.Controls.Add(songsDataGridView)

        songsDataGridView.ColumnCount = 5
        With songsDataGridView.ColumnHeadersDefaultCellStyle
            .BackColor = Color.Navy
            .ForeColor = Color.White
            .Font = New Font(songsDataGridView.Font, FontStyle.Bold)
        End With

        With songsDataGridView
            .Name = "songsDataGridView"
            .Location = New Point(8, 8)
            .Size = New Size(500, 250)
            .AutoSizeRowsMode = _
                DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
            .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
            .CellBorderStyle = DataGridViewCellBorderStyle.Single
            .GridColor = Color.Black
            .RowHeadersVisible = False

            .Columns(0).Name = "Release Date"
            .Columns(1).Name = "Track"
            .Columns(2).Name = "Title"
            .Columns(3).Name = "Artist"
            .Columns(4).Name = "Album"
            .Columns(4).DefaultCellStyle.Font = _
                New Font(Me.songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic)

            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .MultiSelect = False
            .Dock = DockStyle.Fill
        End With

    End Sub

    Private Sub PopulateDataGridView()

        Dim row0 As String() = {"11/22/1968", "29", "Revolution 9", _
            "Beatles", "The Beatles [White Album]"}
        Dim row1 As String() = {"1960", "6", "Fools Rush In", _
            "Frank Sinatra", "Nice 'N' Easy"}
        Dim row2 As String() = {"11/11/1971", "1", "One of These Days", _
            "Pink Floyd", "Meddle"}
        Dim row3 As String() = {"1988", "7", "Where Is My Mind?", _
            "Pixies", "Surfer Rosa"}
        Dim row4 As String() = {"5/1981", "9", "Can't Find My Mind", _
            "Cramps", "Psychedelic Jungle"}
        Dim row5 As String() = {"6/10/2003", "13", _
            "Scatterbrain. (As Dead As Leaves.)", _
            "Radiohead", "Hail to the Thief"}
        Dim row6 As String() = {"6/30/1992", "3", "Dress", "P J Harvey", "Dry"}

        With Me.songsDataGridView.Rows
            .Add(row0)
            .Add(row1)
            .Add(row2)
            .Add(row3)
            .Add(row4)
            .Add(row5)
            .Add(row6)
        End With

        With Me.songsDataGridView
            .Columns(0).DisplayIndex = 3
            .Columns(1).DisplayIndex = 4
            .Columns(2).DisplayIndex = 0
            .Columns(3).DisplayIndex = 1
            .Columns(4).DisplayIndex = 2
        End With

    End Sub


    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())
    End Sub

End Class

System.NullReferenceException datagridview object reference not set to an

instance of an object.

In addition to Sandeep’s answer, I would add e.RowIndex >= 0 && e.ColumnIndex
>= 0 inside if. And IsNullOrEmpty only takes a string as parameter, but
Cell.Value property is of type Object.So you can’t pass it directly to the
IsNullOrEmpty method. Try th something like this:

dataGridView.Rows[e.RowIndex].Cells["ReturnQty"].Value.ToString()


if(!String.IsNullOrEmpty(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
{

       // do sonmthing
}


if(MainGridView.Rows.Count >0 && MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex] != null)
{
   if(!String.IsNullOrEmpty(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value))
   {
       // do sonmthind
   }
}


if(Convert.Tostring(MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value)){       // do sonmthing}


if (MainGridView.Rows.Count > 0 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
   DataGridViewCell cell = MainGridView.Rows[e.RowIndex].Cells[e.ColumnIndex];
   if (cell != null && !String.IsNullOrEmpty(cell.Value as string))
   {
       // do something
   }
}

VS 2010, небольшой проект на WinForms. В качестве бд использую sqlite3.

Обычная таблица dataGridView на форме заполняется данными из базы через DataSource. Если в базе нет null-записей, всё работает отлично. Если вдруг появилась такая, то выдает ошибку ConstraintException и помечает поле восклицательным знаком в красном кружке. Хотя в таблице поле помечено как NULL, т.е. вполне соответствует структуре.

Строка, на которой срабатывает исключение:

//orders - название таблицы
this.ordersTableAdapter.Fill(this.databaseDataSet.Orders);

Если написать обработчик исключений, то можно просто игнорировать это и всё, но я думаю, так делать неправильно. Как можно грамотно избавиться от этой ошибки, чтобы в таблице отображались null поля?

Сам я только изучаю C#, скорее всего, проблема решается элементарно. Пробовал прописывать DefaultCellStyle.NullValue = «none», не помогло.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows 11 панель задач мелкие значки
  • Aim для windows xp
  • Windows 10 нет сетевого окружения
  • Как восстановить проводник в windows 10 по умолчанию
  • Включение всех ядер процессора windows 10 зачем