如何从gridview单元格中添加空值到列表?

时间:2015-06-18 08:55:22

标签: c# linq list datagridview datagridviewtextboxcell

我想在list<string>中输入访客详细信息(标题,名字,中间名姓氏),访客详细信息可以为空。我使用LINQ插入列表中。我已经提到了这个问题对于LINQ代码DataGridView write all values from a column to list

我想要做的就是将文本输入列表中(如果有)或插入空字符串(如果它没有)。现在如果我将文本框留空,则会抛出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;
        }

1 个答案:

答案 0 :(得分:1)

您的问题是您的单元格值可以是字符串,DBNull.Value或null。 null.ToString()会引发object reference not set to instance of an object exception。为避免这种情况,您可以先设置对象as string以除去DBNull.Value,然后使用null-coalescing operator将null设置为空字符串。

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

在你的情况下:

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