Griff Griff - 3 months ago 20
C# Question

Display if statement variable in messagebox

I'm having issues with displaying the variable within a Message box. What I want to do is display in a messagebox which Combobox hasn't been filled in, it will display this in a list within the messagebox and then stop the user from saving to the database. The error is stating that it is a use of an unassigned variable but I have assigned it at the top of the 'if' statement.

private void btnSaveDB_Click(object sender, EventArgs e)
{
if (cmbPolType.SelectedItem == null ||
cmbPolNum.SelectedItem == null ||
cmbTPReg.SelectedItem == null ||
cmbLossType.SelectedItem == null ||
cmbLossDesc.SelectedItem == null ||
cmbInsdFault.SelectedItem == null)
{
string polType, polNum, lossType, lossDesc, tpReg, insdFault = null;

if (cmbPolType.SelectedItem==null)
{
polType = "Policy Type";
}

if (cmbPolNum.SelectedItem==null)
{
polNum = "Policy Number";
}
if (cmbLossType.SelectedItem==null)
{
lossType = "Loss Type";
}
if (cmbLossDesc.SelectedItem ==null)
{
lossDesc = "Loss Description";
}
if (cmbTPReg.SelectedItem==null)
{
tpReg = "TP Reg";
}
if (cmbInsdFault.SelectedItem==null)
{
insdFault = "Insd at Fault";
}

MessageBox.Show("You have not selected options for the following: " + lossDesc );
}

Answer

No lossDesc is not initialized in that way as well as the other strings variables but the insdFault. (The error message points to lossDesc because is the only one used in the remainder of the code).

Instead of initializing each one, I suggest to use a simple List<string> where you add your error messages and type all of them at the end of the test

List<string> missingData = new List<string>();
if (cmbPolType.SelectedItem == null)
    missingData.Add("Policy Type");
if (cmbPolNum.SelectedItem == null)
    missingData.Add("Policy Number");
if (cmbLossType.SelectedItem == null)
    missingData.Add("Loss Type");
if (cmbLossDesc.SelectedItem == null)
    missingData.Add("Loss Description");
if (cmbTPReg.SelectedItem == null)
    missingData.Add("TP Reg");
if (cmbInsdFault.SelectedItem == null)
    missingData.Add("Insd at Fault");

if(missingData.Count > 0)
{
   MessageBox.Show("You have not selected options for the following: " + 
                    Environment.NewLine + 
                    string.Join(Environment.NewLine, missingData.ToArray()));
}
else
{

   ... save to database ? ....
}

This removes the need to use and initialize a bunch of string variables and uses the string.Join method to get the whole error message in a single string with each error on a separate line.