我想将文本框中的元素添加到数组中,但每次尝试添加名称时都会抛出异常。我想在点击按钮后添加元素。
private void Grade_Click(object sender, EventArgs e)
{
string name;
double grade;
nametextbox.Text = "";
gradetextbox.Text = "";
for (int i = 0; i < 10; i++)
{
grade = Convert.ToDouble(gradetextbox.Text);
grades[i] += grade;
name = nametextbox.Text;
names[i] += name;
}
}
答案 0 :(得分:0)
你这样做:
gradetextbox.Text = "";
将Text
属性设置为空字符串。然后你这样做:
grade = Convert.ToDouble(gradetextbox.Text);
试图将空字符串转换为double
,这显然不起作用,因此会引发异常。
你可能需要的是:
private double[] grades = new double[10]; // 10 grades
private string[] names = new string[10]; // 10 names
private int currentIndex = 0;
private void Grade_Click(object sender, EventArgs e)
{
if (currentIndex > 10)
{
MessageBox.Show("No more enteries allowed");
}
string name;
double grade;
if (double.TryParse(gradetextbox.Text, out grade))
{
grades[currentIndex] += grade;
}
else
{
MessageBox.Show("Grade enterd is not a valid grade");
return;// do nothing else
}
name = nametextbox.Text;
names[i] += name;
// now clear the textboxes so user can enter another value
nametextbox.Text = "";
gradetextbox.Text = "";
currentIndex = currentIndex + 1;
}