-2

我想在 a 中输入客人详细信息(Title,Firstname,midname lastname)list<string>,客人详细信息可以为空。我正在使用 LINQ 插入列表。我已经为 LINQ 代码DataGridView 写入了所有值要列出的列

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

1 回答 1

1

您的问题是您的单元格值可以是字符串、DBNull.Value 或 null。 null.ToString()抛出object reference not set to instance of an object exception. 为避免这种情况,您可以首先将对象设置as string为摆脱 DBNull.Value,然后使用null-coalescing 运算符将 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();
于 2015-06-18T09:47:57.050 回答