我想从列表中删除一个项目......
我显然错过了一些东西......我已经尝试了几乎所有的变化,包括EXCEPT,REMOVE等......
调试时,我会逐步浏览每个ling,但是当它到达btnRemove_Click时,它会逐步删除但不删除任何内容......就好像我从未发送命令删除任何内容一样???
帮助!
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;
}
}
答案 0 :(得分:2)
在C#中,字符串是不可变的。 _scores.Remove(i);
不会更改_scores
。相反,它返回一个新的字符串对象,您可以将其分配给变量,例如,返回_scores
,如下所示:
_scores = _scores.Remove(i);
答案 1 :(得分:0)
你需要使用RemoveAt方法 - 因为你试图删除索引而不是值