Search code examples
c#linqlistdatagridviewdatagridviewtextboxcell

How to add empty value from gridview cell to list?


I want to enter guest details(Title,Firstname,midname lastname) in a list<string> ,the guest details can be empty.I'm using LINQ for inserting in the list.I had referred this question for the LINQ code DataGridView write all values from a column to list

All I want to do is enter the text into the list if it has or insert empty string if it doesn't have.Right now if I leave textboxes blank it will throw object reference not set to instance of an object exception

private string SaveGuestDetails()
        {
            string strRet = string.Empty;
            Reservation obj = new Reservation();
            FinalReservationDetails f = new FinalReservationDetails();

            try
            {
                //int i = dgvTextBoxes.Rows.Count;
                List<DataRow> personsList = new List<DataRow>();
                int j = 0;
                for (int i = 0; i < dgvTextBoxes.Rows.Count; i++)
                {
                    f.SubSrNo = j + 1;

                      f.GuestTitle = dgvTextBoxes.Rows
                   .OfType<DataGridViewRow>()
                   .Select(r => r.Cells["txtTitle"].Value.ToString())
                   .ToList();

                f.FirstName = dgvTextBoxes.Rows
                    .OfType<DataGridViewRow>()
                    .Select(r => r.Cells["txtFname"].Value.ToString())
                    .ToList();

                f.MidName = dgvTextBoxes.Rows
                    .OfType<DataGridViewRow>()
                    .Select(r => r.Cells["txtMName"].Value.ToString())
                    .ToList();

                f.LastName = dgvTextBoxes.Rows
                    .OfType<DataGridViewRow>()
                    .Select(r => r.Cells["txtLname"].Value.ToString())
                    .ToList();

                 }


            }
            catch (Exception ex)
            {

            }
            return strRet;
        }

Solution

  • Your problem is that your cell values can be string, DBNull.Value or null. null.ToString() throws the object reference not set to instance of an object exception. To avoid that you can first set your object as string to get rid of the DBNull.Value and then use the null-coalescing operator to set null to empty string.

    object unknown = System.DBNull.Value;
    string converted1 = (unknown as string) ?? string.Empty;
    // returns string.Empty
    
    unknown = null;
    string converted2 = (unknown as string) ?? string.Empty;
    // returns string.Empty
    
    unknown = "text";
    string converted3 = (unknown as string) ?? string.Empty;
    // returns text
    

    In your case:

    f.GuestTitle = dgvTextBoxes.Rows.OfType<DataGridViewRow>().Select
    (r => (r.Cells["txtTitle"].Value as string) ?? string.Empty ).ToList();