Bool property is set to true without being called - c#

I am making an web application for articles reading.
I have bool property which is set to true if the specific Edit Button is clicked, there is also a Save Button which is clicked after filling user information on TextBoxes and other controls. Whenever I run my application and fills information, it runs fine but after 4 or 5 runs (re-starting the application) it gives an Exception error upon clicking Save Button:
Input string was not in a correct format which is due to filling TextBoxes with Null( firstly, Null is converted into Int).
My problem is that bool property (Managment.IsEditing) is set to true without any reason ( Edit Button should be pressed to set bool to true). Why and how is set to true automatically as its code is only being called in EditButton_Click Event?
Here is a code
protected void EditButton_Click(object sender, EventArgs e)
{
if(EditorList.SelectedIndex > -1) //Just to ensure that Item is selected from ListBox
{
//editor is the poco , EditorManager is the editor table manager
editor = EditorManager.GetEditorInfo(EditorList.SelectedValue);
NameTextBox.Text = editor.Name;
EmailTextBox1.Text = editor.Email;
PasswordTextBox.Text = editor.Password;
EditorIDTextBox.Text = editor.Editor_ID.ToString();
for (int index = 0; index < RoleCheckBoxList.Items.Count; index++)
{
RoleCheckBoxList.Items[index].Selected = editor.RoleList[index];
}
Managment.IsEditing = true; //This flag is responsible for telling "SaveButtton" that editor would be updated.
DeleteButton.Enabled = true;
ResultLabel.Text = "";
}
else
ResultLabel.Text = "Select Editor from list first";
protected void SaveButton_Click(object sender, EventArgs e)
{
if(Managment.IsEditing == false) //it makes sure that new editor is being saved
{
editor.Name = NameTextBox.Text;
string email = EmailTextBox1.Text;
editor.Email = email.ToLower();
editor.Password = PasswordTextBox.Text;
if(EditorManager.IsEditorValid(editor.Email))
{
for (int index = 0; index < RoleCheckBoxList.Items.Count; index++)
{
editor.RoleList[index] = RoleCheckBoxList.Items[index].Selected;
}
EditorManager.Save(editor);
ResultLabel.Text = editor.DataUploadMessage;
}
else
ResultLabel.Text = "Editor with the same Email can't be add!";
FillEditorList();
}
else if(Managment.IsEditing == true) //it determines that existing editor is being updated and problem is that Managment.IsEditing is turned on without being called.
{
editor.Name = NameTextBox.Text;
string email = EmailTextBox1.Text;
editor.Email = email.ToLower();
editor.Password = PasswordTextBox.Text;
editor.Editor_ID = Convert.ToInt32(EditorIDTextBox.Text);// Error occurs at this line
for (int index = 0; index < RoleCheckBoxList.Items.Count; index++)
{
editor.RoleList[index] = RoleCheckBoxList.Items[index].Selected;
}
EditorManager.Edit(editor);
ResultLabel.Text = editor.DataUploadMessage;
Managment.IsEditing = false;
FillEditorList();
}
ClearFields(Form.Controls);
}
Exception occurs on that line:
editor.Editor_ID = Convert.ToInt32(EditorIDTextBox.Text);
and sorry for any inconvenience dear fellows

When the exception occurs on the indicated line, the line that resets your flag won't be run. The page will then likely be in an invalid state.
Try fixing/handling the error and clean up properly, and the problem might go away.

Related

How to stop error when clicking index greater than 0 in datagridview?

I am trying to open a form when I click a row in a datagridview and populate the textboxes within the new form. I am able to click the first row (index zero) and it does what I am trying to achieve. But if I click any other row, I get an error:
Here is my code:
private void dataGridViewActivityHire_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
EditFormHire form2 = new EditFormHire();
var table = dataGridViewActivityHire;
string name = table.SelectedRows[e.RowIndex].Cells[0].Value.ToString();
string type = table.SelectedRows[e.RowIndex].Cells[1].Value.ToString();
string cost = table.SelectedRows[e.RowIndex].Cells[3].Value.ToString();
DateTime start = Convert.ToDateTime(table.SelectedRows[e.RowIndex].Cells[4].Value);
DateTime end = Convert.ToDateTime(table.SelectedRows[e.RowIndex].Cells[5].Value);
form2.CustomerName = name;
form2.Registration = textBoxRegistration.Text;
form2.ActivityType = type;
form2.DailyHireCost = textBoxDailyHireCost.Text;
form2.Total = cost;
form2.StartDate = start;
form2.EndDate = end;
form2.ShowDialog();
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
I find it odd that I can click the first index and it works correctly, but any index > 0 returns that error. Anyone know what could be causing this?

How to use DataGridView value as save & load control in C#?

I'm currently making save & load options program with DataGridView. the save button will save picturebox coordinates to make lines based on what already drawn on the picturebox. Multiple save datas are saved as tables in DataGridView. When loaded, the saved coordinates in tables go back to the screen and draw the saved coordinate lines. in the future gonna make the save data can be exported & imported to excel files but for now those buttons is not working yet.
Questions is How to make multiple loads possible? the first save data can be loaded properly after click but the 2nd and next will make the app crashed so the only working save data are the top ones. the error always points to string lineCell = dataGridView1.SelectedRows[rowIndex].Cells[1].Value.ToString(); but I dont know how to fix it
also if have suggestions how to export & import it to excel file please tell me. Thank you very much.
More or less the app is like this
used code for load & delete buttons in datagridview
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
int rowIndex = dataGridView1.CurrentCell.RowIndex;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
{
if (e.ColumnIndex == dataGridView1.Columns[7].Index)
{
string lineCell = dataGridView1.SelectedRows[rowIndex].Cells[1].Value.ToString();
int x1Cell = Convert.ToInt16(dataGridView1.SelectedRows[rowIndex].Cells[3].Value.ToString());
int y1Cell = Convert.ToInt16(dataGridView1.SelectedRows[rowIndex].Cells[4].Value.ToString());
int x2Cell = Convert.ToInt16(dataGridView1.SelectedRows[rowIndex].Cells[5].Value.ToString());
int y2Cell = Convert.ToInt16(dataGridView1.SelectedRows[rowIndex].Cells[6].Value.ToString());
if (lineCell == "Black")
{
lineComboBox.SelectedIndex = 0;
line1X1 = x1Cell;
line1Y1 = y1Cell;
line1X2 = x2Cell;
line1Y2 = y2Cell;
}
else if (lineCell == "Red")
{
lineComboBox.SelectedIndex = 1;
line2X1 = x1Cell;
line2Y1 = y1Cell;
line2X2 = x2Cell;
line2Y2 = y2Cell;
}
else if (lineCell == "Yellow")
{
lineComboBox.SelectedIndex = 2;
line3X1 = x1Cell;
line3Y1 = y1Cell;
line3X2 = x2Cell;
line3Y2 = y2Cell;
}
lineComboBox.Refresh();
pictureBox1.Refresh();
}
else if (e.ColumnIndex == dataGridView1.Columns[8].Index)
{
dataGridView1.Rows.RemoveAt(rowIndex);
}
}
Save Button code
private void saveButton_Click(object sender, EventArgs e)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells[0].Value = "Save " + index.ToString();
dataGridView1.Rows[index].Cells[2].Value = ang;
if(lineComboBox.SelectedIndex == 0)
{
dataGridView1.Rows[index].Cells[1].Value = "Black";
dataGridView1.Rows[index].Cells[3].Value = line1X1;
dataGridView1.Rows[index].Cells[4].Value = line1Y1;
dataGridView1.Rows[index].Cells[5].Value = line1X2;
dataGridView1.Rows[index].Cells[6].Value = line1Y2;
}
else if(lineComboBox.SelectedIndex == 1)
{
dataGridView1.Rows[index].Cells[1].Value = "Red";
dataGridView1.Rows[index].Cells[3].Value = line2X1;
dataGridView1.Rows[index].Cells[4].Value = line2Y1;
dataGridView1.Rows[index].Cells[5].Value = line2X2;
dataGridView1.Rows[index].Cells[6].Value = line2Y2;
}
else if (lineComboBox.SelectedIndex == 2)
{
dataGridView1.Rows[index].Cells[1].Value = "Yellow";
dataGridView1.Rows[index].Cells[3].Value = line3X1;
dataGridView1.Rows[index].Cells[4].Value = line3Y1;
dataGridView1.Rows[index].Cells[5].Value = line3X2;
dataGridView1.Rows[index].Cells[6].Value = line3Y2;
}
}
and this is the error message. Sorry its in japanese the office only use japanese version here. but its roughly translated as this
Unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
Additional Information: Index out of range. Must be non-negative and less than the size of the collection.

DataGridView Deleting/Updating problems

So, I've been doing some practice code for a few days. I'm working on using a DataGridView, without a database. Everything seems to work, save for one problem. Whenever I click the delete or update button without selecting a record, the form crashes. Here's the update function:
private void btnUpdate_Click(object sender, EventArgs e)
{
if (dgvProfiles.SelectedCells == null)
{
MessageBox.Show("No record was selected to update.");
}
else {
for (int row = 0; row < dgvProfiles.Rows.Count; row++)
{
for (int col = 0; col < dgvProfiles.Columns.Count; col++)
{
if (dgvProfiles.Rows[row].Cells[col].Value != null &&
dgvProfiles.Rows[row].Cells[col].Value.Equals(txtEmail.Text.Trim()))
{
MessageBox.Show("Duplicate email was entered.");
return;
}
}
}
DataGridViewRow newDataRow = dgvProfiles.Rows[indexRow];
newDataRow.Cells[0].Value = txtFirstName.Text;
newDataRow.Cells[1].Value = txtLastName.Text;
newDataRow.Cells[2].Value = txtPhone.Text;
newDataRow.Cells[3].Value = txtEmail.Text;
newDataRow.Cells[4].Value = txtCity.Text;
newDataRow.Cells[5].Value = cbxState.Text;
newDataRow.Cells[6].Value = txtZip.Text;
}
}
Thanks in advance!
SelectedCells is a collection the system provides.
It is never null.
It can be emtpy though, so if (for some reason) you want to check you can write :
if (dgvProfiles.SelectedCells.Count <= 0)..
or
if (dgvProfiles.SelectedRows.Count <= 0)..
I'm not sure why you demand a row or cell to be selected in the first place, though. Shouldn't saving always work..?

ComboBox item return index

First of all im sorry for my English. Im a beginner programmer in C# using VS Express 2013.
This is my simple problem i think:
I have a combobox (cboMantello) with two items inside.
Then i have a button that uses the attributes of the selected item and add them into my character stats.
Another button removes that attributes.
To avoid Users spam the first button i disabled it and also set my combobox.enabled to false.
At this point comes up the problem. On disabling the combobox, it returns on the first item in list, so if i select the second item and press the "equipe" buttom it adds the attributes, but then the combobox switch to the first item.So if i push the "remove" button the code remove the first item attributes.
I dont know how tell combobox to frezze on second item during the enabled = false phase.
Thanks for help, and sry again for my grammatical "horrors" !
Heres my code:
private void UpdateListaMantelliInventarioUI()
{
List<Mantello> mantelli = new List<Mantello>();
foreach (OggettoInventario oggettoInventario in _player.Inventario)
{
if (oggettoInventario.Dettagli is Mantello)
{
if (oggettoInventario.Quantità > 0)
{
mantelli.Add((Mantello)oggettoInventario.Dettagli);
}
}
}
if (mantelli.Count == 0)
{
cboMantello.Enabled = false;
}
else
{
cboMantello.DataSource = mantelli;
cboMantello.DisplayMember = "Nome";
cboMantello.ValueMember = "ID";
cboMantello.SelectedIndex = 0;
}
}
private void btMantello_Click(object sender, EventArgs e)
{
Mantello mantellocorrente = (Mantello)cboMantello.SelectedItem;
_player.DifesaMagica = (_player.DifesaMagica + mantellocorrente.AggiungeDifesaMagica);
lblVesteDifesa.Text = "(+" + mantellocorrente.AggiungeDifesaMagica.ToString() + ")";
toolTip1.SetToolTip(lblVesteDifesa, mantellocorrente.Nome.ToString());
_player.Mana = (_player.Mana + mantellocorrente.AggiungeMana);
lblVesteMana.Text = "(+" + mantellocorrente.AggiungeMana.ToString() + ")";
toolTip1.SetToolTip(lblVesteMana, mantellocorrente.Nome.ToString());
_player.Evasione = (_player.Evasione + mantellocorrente.AggiungeEvasione);
lblVesteEvasione.Text = "(+" + mantellocorrente.AggiungeEvasione.ToString() + ")";
toolTip1.SetToolTip(lblVesteEvasione, mantellocorrente.Nome.ToString());
btMantello.Enabled = false;
btTogliMantello.Enabled = true;
cboMantello.Enabled = false;
UpdatePlayerStats();
UpdateListaMantelliInventarioUI();
}
private void btTogliMantello_Click(object sender, EventArgs e)
{
Mantello mantellocorrente = (Mantello)cboMantello.SelectedItem;
if (btMantello.Enabled == false)
{
btTogliMantello.Enabled = true;
_player.DifesaMagica = (_player.DifesaMagica - mantellocorrente.AggiungeDifesaMagica);
lblVesteDifesa.Text = "";
_player.Mana = (_player.Mana - mantellocorrente.AggiungeMana);
lblVesteMana.Text = "";
_player.Evasione = (_player.Evasione - mantellocorrente.AggiungeEvasione);
lblVesteEvasione.Text = "";
UpdatePlayerStats();
btMantello.Enabled = true;
cboMantello.Enabled = true;
}
btTogliMantello.Enabled = false;
}
The reason the Combo Box is resetting is because you are changing its contents when you call UpdateListaMantelliInventarioUI() in the click event for bntMantello, specifically the lines cboMantello.DataSource = mantelli; and cboMantello.SelectedIndex = 0;.
Some options to consider:
Is it necessary to update the combo box after they click equip/unequip?
If it is, you could either add/remove from cboMantello.Items directly.
You could also get the SelectedIndex/Item from cboMantello before you update it. After you update cboMantello, you could loop through the items and update the SelectedIndex/Item.
Some code:
private void UpdateListaMantelliInventarioUI()
{
var previousSelection = cboMantello.SelectedItem;
...
else
{
...
if (cboMantello.Items.Contains(previousSelection))
cboMantello.SelectedItem = previousSelection;
else
cboMantello.SelectedIndex = 0;
}
}

C# DataGridView Stay Focused on Last Record

I have a DataGridView where I am scanning in checks from a keyboard emulated device.
While keypreview is on and I'm waiting for input, the user cannot type anything in otherwise it grabbed by my method to read the input by the check reader. All this is working fine.
After the scan, I am adding to the datagridview a row, which is being put at the end.
How do I make the datagridview scroll to the bottom after each add? I wind up with a few hundred checks and it's at the top. So, every time they scan, they have no idea what was scanned in.
This is my method that creates the row:
private void Timer1Tick(object sender, EventArgs e)
{
_secondswaited += 1;
if (_secondswaited == SecondsToWait)
{
timer1.Enabled = false;
var psc = new ParseScannedCheckNumbers();
if (psc.ParseCheck(_checkData))
{
label_Status.Text = #"Scan Next Check";
var ct = checkTrans.IndividualCheck.NewIndividualCheckRow();
ct.Date = DateTime.Now.ToShortDateString();
ct.AccountNumber = GetAccountNumber(psc.BankAccountNumber);
ct.Name = GetAccountName(ct.AccountNumber);
ct.AccountBalance = GetAccountBalance(ct.AccountNumber);
//ct.CheckAmount = 0;
ct.BankRoutingNumber = psc.BankRoutingNumber;
ct.BankAccountNumber = psc.BankAccountNumber;
ct.CheckNumber = psc.CheckNumber;
ct.Status = "Entered";
checkTrans.IndividualCheck.Rows.Add(ct);
var dgvcount = dgv_Checks.Rows.Count;
**dgv_Checks.Rows[dgvcount - 1].Selected = true;**
}
else
{
label_Status.Text = #"Scan failed. Rescan check.";
}
_checkData = string.Empty;
_secondswaited = 0;
var rs = new Registry.RegistrySettings();
if (!rs.ScanChecksContinuous)
{
StopScanning();
label_Status.Text = #"Success!";
EditLastRowEntered();
}
label_ChecksScanned.Text = (dgv_Checks.RowCount - 1).ToString();
}
}
The part that is bold is where I attempted to move to the last row, without success.
Thanks!
I'd use the DataGridView.CurrentCell property. Try this in place of the line you're having problems with:
dgv_Checks.CurrentCell = dgv_Checks.Rows[dgvcount - 1].Cells[0];
What i think you need to do is check to see if the Row is being displayed.
and then
replace the line in bold with
if(dgv_Checks.Rows[dgvcount - 1].Displayed == false)
{
dgv_Checks.FirstDisplayedScrollingRowIndex = dgvcount - 1;
}

Categories