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;
}
Your problem is that your cell values can be string, DBNull.Value or null.
null.ToString()throws theobject reference not set to instance of an object exception. To avoid that you can first set your objectas stringto get rid of the DBNull.Value and then use the null-coalescing operator to set null to empty string.In your case: