La valeur ne peut pas être null, ArgumentNullException
Je suis en train d'essayer de retourner un tableau qui contient des informations sur un siège à un theate telles que le numéro de Siège, le Nom, le Prix et l'État. Je suis l'aide d'une zone de liste déroulante où je veux la liste de tous les vacant ou des sièges réservés basé sur des choix. Lorsque je choisis de sièges réservés dans ma combobox, je fais appel à une méthode utilisant AddRange. Cette méthode est censée parcourir un tableau contenant tous les sièges et leurs informations. Si un siège est Vacant, je l'ajouter à un tableau. Quand tout est fait, je retourne de ce tableau. Cependant, j'ai affaire à un ArgumentNullException.
MainForm:
namespace Assignment4
{
public partial class MainForm : Form
{
//private const int totNumberOfSeats = 240;
private SeatManager seatMngr;
private const int columns = 10;
private const int rows = 10;
public enum DisplayOptions
{
AllSeats,
VacantSeats,
ReservedSeats
}
public MainForm()
{
InitializeComponent();
seatMngr = new SeatManager(rows, columns);
InitializeGUI();
}
///<summary>
///Fill the listbox with information from the beginning,
///let the user be able to choose from vacant seats.
///</summary>
private void InitializeGUI()
{
rbReserve.Checked = true;
txtName.Text = string.Empty;
txtPrice.Text = string.Empty;
lblTotalSeats.Text = seatMngr.GetNumOfSeats().ToString();
cmbOptions.Items.AddRange(Enum.GetNames(typeof(DisplayOptions)));
cmbOptions.SelectedIndex = 0;
UpdateGUI();
}
///<summary>
///call on methods ValidateName and ValidatePrice with arguments
///</summary>
///<param name="name"></param>
///<param name="price"></param>
///<returns></returns>
private bool ValidateInput(out string name, out double price)
{
bool nameOK = ValidateName(out name);
bool priceOK = ValidatePrice(out price);
return nameOK && priceOK;
}
///<summary>
///Validate name using inputUtility, show error if input is invalid
///</summary>
///<param name="name"></param>
///<returns></returns>
private bool ValidateName(out string name)
{
name = txtName.Text.Trim();
if (!InputUtility.ValidateString(name))
{
//inform user
MessageBox.Show("Input of name is Invalid. It can not be empty, " + Environment.NewLine + "and must have at least one character.", " Error!");
txtName.Focus();
txtName.Text = " ";
txtName.SelectAll();
return false;
}
return true;
}
///<summary>
///Validate price using inputUtility, show error if input is invalid
///</summary>
///<param name="price"></param>
///<returns></returns>
private bool ValidatePrice(out double price)
{
//show error if input is invalid
if (!InputUtility.GetDouble(txtPrice.Text.Trim(), out price, 0))
{
//inform user
MessageBox.Show("Input of price is Invalid. It can not be less than 0, " + Environment.NewLine + "and must not be empty.", " Error!");
txtPrice.Focus();
txtPrice.Text = " ";
txtPrice.SelectAll();
return false;
}
return true;
}
///<summary>
///Check if item is selected in listbox
///</summary>
///<returns></returns>
private bool CheckSelectedIndex()
{
int index = lbSeats.SelectedIndex;
if (index < 0)
{
MessageBox.Show("Please select an item in the box");
return false;
}
else
return true;
}
///<summary>
///Call method ReserveOrCancelSeat when button OK is clicked
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void btnOK_Click(object sender, EventArgs e)
{
ReserveOrCancelSeat();
}
///<summary>
///Reserve or cancel seat depending on choice the user makes. Update GUI after choice.
///</summary>
private void ReserveOrCancelSeat()
{
if (CheckSelectedIndex() == true)
{
string name = string.Empty;
double price = 0.0;
int selectedSeat = lbSeats.SelectedIndex;
bool reserve = false;
bool cancel = false;
if (rbReserve.Checked)
{
DialogResult result = MessageBox.Show("Do you want to continue?", "Approve", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
if (ValidateInput(out name, out price))
{
reserve = seatMngr.ReserveSeat(name, price, selectedSeat);
if (reserve == true)
{
MessageBox.Show("Seat has been reserved");
UpdateGUI();
}
else
{
MessageBox.Show("Seat has already been reserved");
}
}
}
}
else
{
DialogResult result = MessageBox.Show("Do you want to continue?", "Approve", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
cancel = seatMngr.CancelSeat(selectedSeat);
if (cancel == true)
{
MessageBox.Show("Seat has been cancelled");
UpdateGUI();
}
else
{
MessageBox.Show("Seat is already vacant");
}
}
}
UpdateGUI();
}
}
///<summary>
///Update GUI with new information.
///</summary>
///<param name="customerName"></param>
///<param name="price"></param>
private void UpdateGUI()
{
lbSeats.Items.Clear();
lbSeats.Items.AddRange(seatMngr.GetSeatInfoString());
lblVacantSeats.Text = seatMngr.GetNumOfVacant().ToString();
lblReservedSeats.Text = seatMngr.GetNumOfReserved().ToString();
if (rbReserve.Checked)
{
txtName.Text = string.Empty;
txtPrice.Text = string.Empty;
}
}
///<summary>
///set textboxes to false if cancel reservation button is checked
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void rbCancel_CheckedChanged_1(object sender, EventArgs e)
{
txtName.Enabled = false;
txtPrice.Enabled = false;
}
///<summary>
///set textboxes to true if reserved radiobutton is checked
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void rbReserve_CheckedChanged_1(object sender, EventArgs e)
{
txtName.Enabled = true;
txtPrice.Enabled = true;
}
///<summary>
///Make necessary changes on the list depending on what choice the user makes. Show only
///what the user wants to see, whether its all seats, reserved seats or vacant seats only.
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
private void cmbOptions_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbOptions.SelectedIndex == 0 && rbReserve.Checked) //All seats visible.
{
UpdateGUI();
txtName.Enabled = true;
txtPrice.Enabled = true;
btnOK.Enabled = true;
}
else if (cmbOptions.SelectedIndex == 0 && rbCancel.Checked)
{
UpdateGUI();
txtName.Enabled = false;
txtPrice.Enabled = false;
btnOK.Enabled = true;
}
else if (cmbOptions.SelectedIndex == 1) //Only vacant seats visible.
{
lbSeats.Items.Clear();
lbSeats.Items.AddRange(seatMngr.ReturnVacantSeats()); //Value cannot be null
txtName.Enabled = false;
txtPrice.Enabled = false;
btnOK.Enabled = false;
}
else if (cmbOptions.SelectedIndex == 2) //Only reserved seats visible.
{
lbSeats.Items.Clear();
lbSeats.Items.AddRange(seatMngr.ReturnReservedSeats()); //Value cannot be null
txtName.Enabled = false;
txtPrice.Enabled = false;
btnOK.Enabled = false;
}
}
}
}
SeatManager:
namespace Assignment4
{
class SeatManager
{
private string[,] nameList = null;
private double[,] priceList = null;
private string[,] seatList = null;
private readonly int totCols;
private readonly int totRows;
///<summary>
///Constructor with declarations of size for all arrays.
///</summary>
///<param name="totNumberOfSeats"></param>
public SeatManager(int row, int cols)
{
totCols = cols;
totRows = row;
nameList = new string[row, cols];
priceList = new double[row, cols];
seatList = new string[row, cols];
for (int rows = 0; rows < row; rows++)
{
for (int col = 0; col < totCols; col++)
{
seatList[rows, col] = "Vacant";
}
}
}
}
}
///<summary>
///Check if index is within bounds of the array
///</summary>
///<param name="index"></param>
///<returns></returns>
private bool CheckIndex(int index)
{
if (index >= 0 && index < nameList.Length)
return true;
else
return false;
}
///<summary>
///Return total number of seats
///</summary>
///<returns></returns>
public int GetNumOfSeats()
{
int count = 0;
for (int rows = 0; rows < totRows; rows++)
{
for (int cols = 0; cols < totCols; cols++)
{
count++;
}
}
return count;
}
///<summary>
///Calculate and return total number of reserved seats
///</summary>
///<returns></returns>
public int GetNumOfReserved()
{
int totReservedSeats = 0;
for (int rows = 0; rows < totRows; rows++)
{
for (int col = 0; col < totCols; col++)
{
if (!string.IsNullOrEmpty(nameList[rows, col]))
{
totReservedSeats++;
}
}
}
return totReservedSeats;
}
///<summary>
///Calculate and return total number of vacant seats
///</summary>
///<returns></returns>
public int GetNumOfVacant()
{
int totVacantSeats = 0;
for (int rows = 0; rows < totRows; rows++)
{
for (int col = 0; col < totCols; col++)
{
if (string.IsNullOrEmpty(nameList[rows, col]))
{
totVacantSeats++;
}
}
}
return totVacantSeats;
}
///<summary>
///Return formated string with info about the seat, name, price and its status
///</summary>
///<param name="index"></param>
///<returns></returns>
public string GetSeatInfoAt(int index)
{
int cols = ReturnColumn(index);
int rows = ReturnRow(index);
string strOut = string.Format("{0,2} {1,10} {2,17} {3,20} {4,35:f2}",
rows+1, cols+1, seatList[rows, cols], nameList[rows, cols], priceList[rows, cols]);
return strOut;
}
///<summary>
///Send an array containing all seats in the cinema
///</summary>
///<returns></returns>
public string[] GetSeatInfoString()
{
int count = totRows * totCols;
if (count <= 0)
return null;
string[] strSeatInfoStrings = new string[count];
for (int i = 0; i < totRows * totCols; i++)
{
strSeatInfoStrings[i] = GetSeatInfoAt(i);
}
return strSeatInfoStrings;
}
///<summary>
///Reserve seat if seat is vacant
///</summary>
///<param name="name"></param>
///<param name="price"></param>
///<param name="index"></param>
///<returns></returns>
public bool ReserveSeat(string name, double price, int index)
{
int cols = ReturnColumn(index);
int rows = ReturnRow(index);
if (string.IsNullOrEmpty(nameList[rows, cols]))
{
nameList[rows, cols] = name;
priceList[rows, cols] = price;
seatList[rows, cols] = "Reserved";
return true;
}
else
return false;
}
public string[] ReturnVacantSeats()
{
int totVacantSeats = int.Parse(GetNumOfVacant().ToString());
string[] vacantSeats = new string[totVacantSeats];
for (int i = 0; i < vacantSeats.Length; i++)
{
if (GetSeatInfoAt(i) == "Vacant")
{
vacantSeats[i] = GetSeatInfoAt(i);
}
}
return vacantSeats;
}
public string[] ReturnReservedSeats()
{
int totReservedSeats = int.Parse(GetNumOfReserved().ToString());
string[] reservedSeats = new string[totReservedSeats];
for (int i = 0; i < reservedSeats.Length; i++)
{
if (GetSeatInfoAt(i) == "Reserved")
{
reservedSeats[i] = GetSeatInfoAt(i);
}
}
return reservedSeats;
}
///<summary>
///Cancel seat if seat is reserved
///</summary>
///<param name="index"></param>
///<returns></returns>
public bool CancelSeat(int index)
{
int cols = ReturnColumn(index);
int rows = ReturnRow(index);
if (!string.IsNullOrEmpty(nameList[rows, cols]))
{
nameList[rows, cols] = "";
priceList[rows, cols] = 0.0;
seatList[rows, cols] = "Vacant";
return true;
}
else
{
return false;
}
}
///<summary>
///Convert index to row and return value
///</summary>
///<param name="index"></param>
///<returns></returns>
public int ReturnRow(int index)
{
int vectorRow = index;
int row;
row = (int)Math.Ceiling((double)(vectorRow / totCols));
return row;
}
///<summary>
///Convert index to column and return value
///</summary>
///<param name="index"></param>
///<returns></returns>
public int ReturnColumn(int index)
{
int row = index;
int col = row % totCols;
return col;
}
Dans MainForm, c'est là que je reçois ArgumentNullException:
lbSeats.Items.AddRange(seatMngr.ReturnVacantSeats());
Et c'est la méthode où le tableau est retourné contenant tous les sièges vacants:
public string[] ReturnVacantSeats()
{
int totVacantSeats = int.Parse(GetNumOfVacant().ToString());
string[] vacantSeats = new string[totVacantSeats];
for (int i = 0; i < vacantSeats.Length; i++)
{
if (GetSeatInfoAt(i) == "Vacant")
{
vacantSeats[i] = GetSeatInfoAt(i);
}
}
return vacantSeats;
}
- Un certain nombre de choses pourraient être null. Je vous suggère de lancer le débogueur et inspecter vos champs et des variables au moment de l'exception.
- Veuillez étroit que c'est à un sscce.org
- Oui je suis d'accord de mettre un point d'arrêt sur le retour de sièges à pourvoir et si sa nul c'est plus probable que votre problème si ce n'ses lbSeats.les éléments les plus susceptibles de jeter l'exception
- FWIW
int.Parse(GetNumOfVacant().ToString());
peut être simplifié à seulementGetNumOfVacant();
depuis que la fonction retourne déjà unint
- J'ai mis un point d'arrêt et là est le problème: si (GetSeatInfoAt(i) == "Vacant") { vacantSeats[i] = GetSeatInfoAt(i); } je suis en train d'essayer d'obtenir l'information de la mauvaise méthode, car il ne marche pas contenir les informations dont j'ai besoin. Ty, ça pourrait aider.
- Vous utilisez une instruction if dans votre ReturnVacantSeats méthode. si le siège info ne correspond pas à Vacants que les tableaux indice de séjour null.
Vous devez vous connecter pour publier un commentaire.
wooolie,
Les commentaires sont vous indiquant que vous avez le nul problème à cause de la
if
déclaration, par conséquent, vous devez éviter d'ajouter des valeurs qui contiennent la valeur null pour votre addrange appel. L'Option n ° 1 serait de changerlbSeats.Items.AddRange(seatMngr.ReturnVacantSeats());
.Ici, vous pouvez ajouter une clause `where' le long de la lignes de (code non testé):
Si vous préférez ne pas le faire, vous pouvez définir la table initiale avec la chaîne vide par défaut les valeurs (cela permettra d'éviter null exceptions).
option #2 (changement):
à:
désordre frigo, pourrait fonctionner, peut-être total b@llocks, mais pourrait obtenir vous-delà de l'erreur pour l'instant.
L'alternative, bien sûr (en code) serait l'option #3:
ouf...
seatList[rows, cols] = "Vacant";
). peut-être que la Liste est plus indulgent, en raison du fait qu'il crée initialisation d'objets que nécessaire.GetSeatInfoAt
est une concaténation de beaucoup de propriétés, dontVacant
est partie!! doh. cependant, être TRÈS prudent pour l'avenir proffing ce, au cas où, pour quelque étrange raison, vous finissez par avoir un "Monsieur Vacant" réservé des sièges!!string
case à la recherche d'une valeur valide (pour les biens), mais se trouve dans une chaîne concaténée dérivés de la Propriété B. Vous avez besoin de changer cette logique, le plus tôt possible, sinon, vous aurez certainement des cas limites qui vous causent des indicibles sessions de débogage dans l'avenir. Ma suggestion serait de l'embrasser plus complet des objets de la classe qui peut gérer plusieurs état et, ainsi, être interrogé via le graphe d'objets, plutôt que de la recherche/validation via concateneted chaînes d'état... allez-y!!