Having problems removing a string from a sting list - c#

I want to remove an item from a list...
I am obviously missing something...I have tried just about every variation including EXCEPT, REMOVE, etc...
When debugging, I step through each ling, but when it gets to btnRemove_Click, it steps through removing but does not remove anything...it acts as if I never sent a command to remove anything???
Help!
public partial class frmUpdate : Form
{
private Student student = new Student();
private string _scores;
public frmUpdate()
{
InitializeComponent();
}
public string GetUpdatedScores(Student s)
{
txtName.Text = s.Name;
_scores = s.Scores;
FillStudentGrades();
this.ShowDialog();
return _scores;
}
private void FillStudentGrades()
{
lstScores.Items.Clear();
string[] grades = splitGrades(_scores);
foreach (string s in grades)
{
lstScores.Items.Add(s.ToString());
}
}
private void lstScores_SelectedIndexChanged(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnAdd_Click(object sender, EventArgs e)
{
frmAddScore addScore = new frmAddScore();
_scores += " " + addScore.AddScore();
FillStudentGrades();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnRemove_Click(object sender, EventArgs e)
{
int i = lstScores.SelectedIndex;
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (lstScores.SelectedIndex < 0)
{
MessageBox.Show("You Must Select A Grade.");
btnUpdate.Focus();
}
else
{
int i = lstScores.SelectedIndex;
string[] grades = splitGrades(_scores);
string message = "Are you sure you want to remove " + grades[i].ToString() + "?";
DialogResult button = MessageBox.Show(message, "Confirm Remove",
MessageBoxButtons.YesNo);
if (button == DialogResult.Yes)
{
int count = 0;
foreach (char c in grades[i])
{
if (char.IsDigit(c))
{
count++;
}
}
int a = _scores.IndexOf(grades[i].ToString());
_scores = _scores.Remove(a, (count + 1));
FillStudentGrades();
btnOk.Focus();
}
else
{
btnOk.Focus();
}
}
}
private void btnClearAll_Click(object sender, EventArgs e)
{
}
private void btnOk_Click(object sender, EventArgs e)
{
student.Name = txtName.Text;
student.Scores = _scores;
this.Close();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
public string[] splitGrades(string s)
{
string[] grades = s.Split(' ');
return grades;
}
}

In C#, strings are immutable. _scores.Remove(i); doesn't change _scores. Instead it returns a new string object that you can assign to a variable, for example, back to _scores like this:
_scores = _scores.Remove(i);

you need to use RemoveAt methos - as you are trying to remove index and not the value

Related

How to avoid user being able to create a Double Booking in a database?

Basically I would like to stop my system from allowing the user to be able to create multiple bookings under the same time slot for a booking if that makes sense. My system basically allows a user to make a booking for a walk, and ideally each walk should only be able to be booked from Monday to Sunday during working hours, but a slot should be 1.5 hours each but at the moment, there is no slots, just the date time pickers for the time and date of the booking and for multiple bookings the user can just pick the same time so i do want to get that fixed.
Hopefully this helps- I have attached my code for my "add booking" form so hopefully thats of some use.
public partial class AddBooking : Form
{
private int count;
private Boolean IsEmpty = false;
private static string _connectionstring = ConfigurationManager.ConnectionStrings["DoggieConnectionString"].ConnectionString;
public AddBooking()
{
InitializeComponent();
CenterToScreen();
GenerateBookingNumber();
IDDisplay.Text = "" + count;
dateTimePicker2.Format = DateTimePickerFormat.Custom;
dateTimePicker2.CustomFormat = "HH:mm tt";
dateTimePicker2.ShowUpDown = true;
DateTime now = DateTime.Now;
}
private void AddBooking_Load(object sender, EventArgs e)
{
}
private int GenerateBookingNumber()
{
string smt = "SELECT COUNT(*) FROM dbo.Booking";
count = 0;
using (SqlConnection connection = new SqlConnection(_connectionstring))
{
using (SqlCommand cmdCount = new SqlCommand(smt, connection))
{
connection.Open();
count = (int)Convert.ToInt32(cmdCount.ExecuteScalar());
}
}
count = count + 4;
return count;
}
private void PresenceCheck()
{
if (string.IsNullOrEmpty(WalkLocationtxt.Text) || string.IsNullOrEmpty(StaffIDtxt.Text))
{
IsEmpty = true;
}
else
{
IsEmpty = false;
}
}
private void SubmitInfobtn_Click(object sender, EventArgs e)
{
// MessageBox.Show("welcome " + dateTimePicker1.Value.ToShortDateString());
// MessageBox.Show("Goodddd" + dateTimePicker2.Value.ToShortTimeString());
PresenceCheck();
if (IsEmpty == false)
{
int rowsareaffected = ClassDatabase.AddBookingDetails(Convert.ToInt32(IDDisplay.Text), dateTimePicker1.Value.ToShortDateString(), dateTimePicker2.Value.ToShortTimeString(), Convert.ToInt32(StaffIDtxt.Text), WalkLocationtxt.Text);
if (rowsareaffected > 0)
{
MessageBox.Show("New Booking Added Sucessfully", "Sucess!", MessageBoxButtons.OK, MessageBoxIcon.Information);
StaffIDtxt.Clear();
WalkLocationtxt.Clear();
GenerateBookingNumber();
IDDisplay.Text = "" + count;
}
else
{
MessageBox.Show("An Error Occurred", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
}
private void mENUToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void returnToMenuToolStripMenuItem_Click(object sender, EventArgs e)
{
new MenuScreen().Show();
this.Close();
}
private void logOutToolStripMenuItem_Click(object sender, EventArgs e)
{
new LoginScreen().Show();
this.Close();
}
private void exitSystemToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult Result = MessageBox.Show("Are you sure you want to Exit the JD Dog Care Program?", "Are You Sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Hand);
if (Result == DialogResult.Yes)
{
Application.Exit();
}
else
{
}
}
private void addClientToolStripMenuItem_Click(object sender, EventArgs e)
{
new AddClient().Show();
this.Close();
}
private void manageClientsToolStripMenuItem_Click(object sender, EventArgs e)
{
new ViewClient().Show();
this.Close();
}
private void addDogsToolStripMenuItem_Click(object sender, EventArgs e)
{
new AddDog().Show();
this.Close();
}
private void manageDogsToolStripMenuItem_Click(object sender, EventArgs e)
{
new ViewDog().Show();
this.Close();
}
private void addStaffToolStripMenuItem_Click(object sender, EventArgs e)
{
new AddStaff().Show();
this.Close();
}
private void manageStaffToolStripMenuItem_Click(object sender, EventArgs e)
{
new ViewStaff().Show();
this.Close();
}
private void addBookingToolStripMenuItem_Click(object sender, EventArgs e)
{
new AddBooking().Show();
this.Close();
}
private void manageBookingToolStripMenuItem_Click(object sender, EventArgs e)
{
new ViewBooking().Show();
this.Close();
}
private void addDogToBookingToolStripMenuItem_Click(object sender, EventArgs e)
{
new DogToWalk().Show();
this.Close();
}
}
}

How to conbine two diffrence label's number to a new label?

I need to calculate the Lb1SumF plus Lb2SumF equal Lb3SumF.
I ran it, and somehow the label3 does not display the expected result.
Here is a screenshot from result.
Here is my code.
private void Form1_Load(object sender, EventArgs e)
{
TX1.TabIndex=0;
}
private void TX1_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb1PriceF.Text) * Convert.ToInt32(TX1.Text);
Lb1SumF.Text = Convert.ToString(sumF); //Label1 sum
}
catch
{
Lb1SumF.Text = "0";
}
}
private void TX2_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb2PriceF.Text) * Convert.ToInt32(TX2.Text);
Lb2SumF.Text = Convert.ToString(sumF); //Label2 sum
}
catch
{
Lb2SumF.Text = "0";
}
}
private void Lb3_TextChanged(object sender, EventArgs e)
{
int i = Convert.ToInt32(Lb1SumF.Text);
int j = Convert.ToInt32(Lb2SumF.Text);
Lb3.Text = Convert.ToString(i+j); // Label3 sum
}
Lb3_TextChanged might never be invoked as you are not changing the text of the label. I would suggest to change it to a private method and not an event handler. Here is what the code could be like:
private void TX1_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb1PriceF.Text) * Convert.ToInt32(TX1.Text);
Lb1SumF.Text = Convert.ToString(sumF); //Label1 sum
// Call to update sum
UpdateSum();
}
catch
{
Lb1SumF.Text = "0";
}
}
private void TX2_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
sumF = Convert.ToInt32(Lb2PriceF.Text) * Convert.ToInt32(TX2.Text);
Lb2SumF.Text = Convert.ToString(sumF); //Label2 sum
// Call to update sum
UpdateSum();
}
catch
{
Lb2SumF.Text = "0";
}
}
// private void Lb3_TextChanged(object sender, EventArgs e)
private void UpdateSum()
{
int sum = 0;
if(!string.IsNullOrEmpty(Lb1SumF.Text) && !string.IsNullOrEmpty(Lb2SumF.Text))
{
sum = Convert.ToInt32(Lb1SumF.Text) + Convert.ToInt32(Lb2SumF.Text);
}
Lb3.Text = Convert.ToString(sum);
}
Replace you code with this it will work, you are using * operator where you have to use + operator, I have commented that lines in your code and replaced it for better understanding.
Happy Coding
namespace WindowsFormsApp8
{
public partial class Form1 : Form
{
private void Lb1SumF_Click(object sender, EventArgs e)
{
}
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
TX1.TabIndex=0;
}
private void label4_Click(object sender, EventArgs e)
{
}
private void TX1_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
//sumF = Convert.ToInt32(Lb1PriceF.Text) * Convert.ToInt32(TX1.Text); // You were doing wrong here , you were multiplying these values
sumF = Convert.ToInt32(Lb1PriceF.Text) + Convert.ToInt32(TX1.Text);
Lb1SumF.Text = Convert.ToString(sumF); //Label1 sum
}
catch
{
Lb1SumF.Text = "0";
}
}
private void TX2_TextChanged(object sender, EventArgs e)
{
try
{
int sumF;
//sumF = Convert.ToInt32(Lb2PriceF.Text) * Convert.ToInt32(TX2.Text); //you are doing it wrong here , you are multiplying
sumF = Convert.ToInt32(Lb2PriceF.Text) + Convert.ToInt32(TX2.Text);
Lb2SumF.Text = Convert.ToString(sumF); //Label2 sum
}
catch
{
Lb2SumF.Text = "0";
}
}
private void Lb3_TextChanged(object sender, EventArgs e)
{
int i = Convert.ToInt32(Lb1SumF.Text);
int j = Convert.ToInt32(Lb2SumF.Text);
Lb3.Text = Convert.ToString(i+j); // Label3 sum
}
private void Lb3SumF_Click(object sender, EventArgs e)
{
}
}
}

ArgumentOutOfRangeException on an object listview when hitting tab

I have an object list view that has two text columns. When I edit the left column and hit tab to go to the right I receive a "ArgumentOutOfRangeException" with an index of -1. Looks like the index is something internal to the list view because I debugged my application and found no errors. Here is the code :
public partial class SummaryOverviewSettingsDlg : Form
{
private List<SummaryDataset> _localSummaryDatasets = new List<SummaryDataset>();
private bool _includeLimits;
private SummaryOverviewSettings _summaryOverviewSettings;
public bool IncludeLimits { get { return _includeLimits; } }
public SummaryOverviewSettingsDlg(SummaryOverviewSettings summaryOverviewSettings)
{
InitializeComponent();
if (summaryOverviewSettings.Datasets != null)
{
_localSummaryDatasets.AddRange(summaryOverviewSettings.Datasets);
}
_summaryOverviewSettings = summaryOverviewSettings;
}
private void DataFilesListDlg_Load(object sender, EventArgs e)
{
foreach(var dataFile in _localSummaryDatasets)
{
olvFilePaths.AddObject(dataFile);
}
LimitsCheckbox.Checked = _summaryOverviewSettings.ShowLimits;
}
private void OlvFilePaths_CellRightClick(object sender, CellRightClickEventArgs e)
{
var contextMenuSymbol = new ContextMenuStrip();
ToolStripItem item;
item = contextMenuSymbol.Items.Add("Add sample");
item.Click += ContextMenuAddFilePath;
if (e.Model != null)
{
contextMenuSymbol.Items.Add("-");
item = contextMenuSymbol.Items.Add("Delete sample");
item.Click += ContextMenuDeleteFilePath;
}
olvFilePaths.ContextMenuStrip = contextMenuSymbol;
}
private void ContextMenuAddFilePath(object sender, EventArgs e)
{
var item = new SummaryDataset()
{
SampleName = "Sample",
Path = "Path"
};
_localSummaryDatasets.Add(item);
// Rebuild the list in the GUI
olvFilePaths.ClearObjects();
foreach (var dataFile in _localSummaryDatasets)
{
olvFilePaths.AddObject(dataFile);
}
olvFilePaths.AutoResizeColumns();
}
private void ContextMenuDeleteFilePath(object sender, EventArgs e)
{
if (olvFilePaths.SelectedObject != null)
{
var item = (SummaryDataset)olvFilePaths.SelectedObject;
olvFilePaths.RemoveObject(item);
_localSummaryDatasets.Remove(item);
}
}
private void OlvFilePaths_CellEditFinished(object sender, CellEditEventArgs e)
{
if (e.Control is TextBox textBox)
{
var oldValue = (string)e.Value;
var newValue = (string)e.NewValue;
var col = e.Column.AspectName;
var index = e.ListViewItem.Index;
if (newValue != oldValue)
{
if (col == "SampleName")
{
_localSummaryDatasets[index].SampleName = newValue;
}
else
{
_localSummaryDatasets[index].Path = newValue;
}
}
}
// Rebuild the list in the GUI
olvFilePaths.ClearObjects();
foreach (var dataFile in _localSummaryDatasets)
{
olvFilePaths.AddObject(dataFile);
}
olvFilePaths.AutoResizeColumns();
}
private void OkButton_Click(object sender, EventArgs e)
{
_summaryOverviewSettings.Datasets.Clear();
_summaryOverviewSettings.Datasets.AddRange(_localSummaryDatasets);
_summaryOverviewSettings.ShowLimits = _includeLimits;
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void LimitsCheckbox_CheckedChanged(object sender, EventArgs e)
{
_includeLimits = LimitsCheckbox.Checked;
}
}

C# text from textbox to string array

I want to add text from textbox to string[] array by pressing button3 i value will add to new array and clear textbox.
Button1 is to go up on array and Button2 is for go down.
I make this but it wont work:
namespace Test
{
public partial class Form1 : Form
{
public int arr1 = 0;
public int arr2 = 0;
public string[] array = new string[100];
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (arr1 < array.Length - 1)
{
if (array[arr1] != "")
{
arr1++;
textBox1.Text = array[arr1];
}
}
else
{
arr1 = 0;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (arr1 < array.Length - 1)
{
if (array[arr1] != "")
{
arr1--;
textBox1.Text = array[arr1];
}
}
else
{
arr1 = 0;
}
}
private void button3_Click(object sender, EventArgs e)
{
array[arr1] = textBox1.Text;
listBox1.Items.Add(array[arr1]);
arr2++;
textBox1.Text = "";
}
}
}
Can someone help me with this?
Thanks
replace arr2++ by arr1++ as following
private void button3_Click(object sender, EventArgs e)
{
array[arr1] = textBox1.Text;
listBox1.Items.Add(array[arr1]);
arr1++;
textBox1.Text = "";
}

C# How do I use a value from one function in another?

How can I use a value from the reading function in the button1_Click function?
public void reading(object sender, EventArgs e)
{
DialogResult reading_from_folder = new DialogResult();
reading_from_folder = folderBrowserDialog1.ShowDialog();
if (reading_from_folder == DialogResult.OK)
{
string[] files_in_folder = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
...
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (string file in files_in_folder) // How do I access files_in_folder?
{
ListViewItem li = new ListViewItem(file);
}
}
You need to store it somehow, for example as a private member:
string some_value = null;
public void reading(object sender, EventArgs e)
{
some_value = "Foobar";
}
private void button1_Click(object sender, EventArgs e)
{
if (some_value != null)
{
// ...
}
}
// Make it a member variable
private string[] mFilesInFolder = null;
public void reading(object sender, EventArgs e)
{
DialogResult reading_from_folder = new DialogResult();
reading_from_folder = folderBrowserDialog1.ShowDialog();
if (reading_from_folder == DialogResult.OK)
{
mFilesInFolder = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
}
}
private void button1_Click(object sender, EventArgs e)
{
DoFileInFolderOperation();
}
private void DoFilesInFolderOperation()
{
if(mFilesInFolder != null)
{
foreach (string file in mFilesInFolder)
{
ListViewItem li = new ListViewItem(file);
}
}
}

Categories

Resources