如何通过使用数组元素的值来获取文本框的值?

时间:2016-05-10 14:42:41

标签: c#

我有14个字段都接受与特定功能一起使用的相同数据类型。我想避免必须使用我当前的内容循环14次。我需要找到一种方法来获取文本框对象,方法是使用数组元素的值作为文本框的引用。例如。阵列[I]。文本。我怎么能这样做?

使用以下简要示例:

if(grades[0] != assignmentEarnedTB[i].Text && grades[1] != assignmentPossTB[i].Text){

正如所料,上面的代码给出了错误字符串不包含Text的定义。

以下是代码的其余部分,向您展示我的意思......

string[] assignmentNames = {"Assignment 1", "Assignment 2", "Assignment 3", "Assignment 4", "Assignment 5", "Assignment 6", "Assignment 7", "Assignment 8", "Assignment 9", "Assignment 10", "Quiz 1", "Quiz 2", "Midterm Project", "Final Project"};
string[] assignmentEarnedTB = {"txtAsmt1Earned", "txtAsmt2Earned", "txtAsmt3Earned", "txtAsmt4Earned", "txtAsmt5Earned", "txtAsmt6Earned", "txtAsmt8Earned", "txtAsmt9Earned", "txtAsmt10Earned", "txtQuiz1Earned", "txtQuiz2Earned", "txtMidtermEarned", "txtFinalEarned"};
string[] assignmentPossTB = {"txtAsmt1Poss","txtAsmt2Poss", "txtAsmt3Poss", "txtAsmt4Poss", "txtAsmt5Poss", "txtAsmt6Poss", "txtAsmt7Poss", "txtAsmt8Poss", "txtAsmt9Poss", "txtAsmt10Poss", "txtQuiz1Poss", "txtQuiz2Poss", "txtMidtermPoss", "txtFinalPoss"};

for(int i = 0; i < assignmentNames.Length; i++){

    string gradeString = proxy.GetAssignmentScore(Convert.ToInt32(Request.QueryString["id"]), assignmentNames[i]);
    string[] grades = gradeString.Split("/");

    if(grades[0] != assignmentEarnedTB[i].Text && grades[1] != assignmentPossTB[i].Text){
        if(txtAsmt1Earned.Text != "" && txtAsmt1Poss.Text != "" && ){
            if (Convert.ToInt32(txtAsmt1Earned.Text) < Convert.ToInt32(txtAsmt1Poss.Text))
            {
                proxy.UpdateAssignmentScore(Convert.ToInt32(Request.QueryString["id"]), "Assignment 1", Convert.ToInt32(txtAsmt1Earned.Text), Convert.ToInt32(txtAsmt1Poss.Text));
            }
            else
            {
                proxy.AddAssignmentScore(Convert.ToInt32(Request.QueryString["id"]), "Assignment 1", Convert.ToInt32(txtAsmt1Earned.Text), Convert.ToInt32(txtAsmt1Poss.Text));
            }
        }
    }

}

2 个答案:

答案 0 :(得分:0)

不要将TextBoxes的名称保留在assignmentEarnedTBassignmentPossTB中,而是自己保留TextBox个引用。

TextBox[] assignmentEarnedTB = new [] { txtAsmt1Earned, txtAsmt2Earned, ... }

您当前的实现仅保留string个对象,其值与您的TextBox对象的名称相同。您没有逻辑要求您要访问名为assignmentEarnedTB[i]的控件。正确地这样做有点麻烦,因此,最好向前迈出一步,而不是保留TextBox个对象的集合而不是它们的名称。

答案 1 :(得分:0)

我不太确定我能完全回想起这些东西的对象名称,但这种方法的本质就足够了:

Control[] assignmentEarnedTB = { txtAsmt1Earned, txtAsmt2Earned, txtAsmt3Earned, ... };
Control[] assignmentPossTB = { txtAsmt1Poss, txtAsmt2Poss, txtAsmt3Poss, ... };

因此,通过排列实际的对象引用,使用整数下标的代码开始工作。