1

我对这个主题很陌生,很迷茫。我的网站上有一个文本框。输入到文本框的数据将被放入一个数组中,并且计数器会增加。一旦计数器达到 5,您就不能向数组中添加更多。

将有一个按钮显示输入到数组中的所有名称,这也清除了数组和计数器。

我不知道如何在 C# 中排序类和方法。我将按钮放在主类中,以便我可以在它们之间共享变量,但是我无法访问文本框。

那里有一些代码,因为我试图弄清楚这一点,但它可能不属于这里。代码也相当简单,因为我只是想弄清楚。任何帮助表示赞赏。

<script runat="server"> 

public partial class Arrays
{
  private int Counter = 0;    

  protected void btnEnter_Click(object sender, EventArgs e)
  {
    Button btn = (Button)sender;
    btn.Text = (Int32.Parse(btn.Text) + 1).ToString();
    Label1.Text = "Enter Another student's name";
  }

  public void btnEnter_Click2(object sender, EventArgs e)
  {
     Label1.Text = "Enter a student's name ";        
  }
}

</script>
4

1 回答 1

0

首先,您需要关注如何将以前的数据保留在页面上。

从 Post 到 Post,您可以将它们存储在ViewStateether 上的control.

正如我所见,在 上保存了以前的状态btn.Text,这不是很酷,但可以接受。

protected void btnEnter_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
     // the btn.Text keeps the number of post backs (enters of name).
    var Counter = Int32.Parse(btn.Text);
    Counter++;

    if(Counter >= 5)
    {   
        Label1.Text = "No more studen's names please";
    }
    else
    {    
        btn.Text = Counter.ToString();          
        Label1.Text = "Enter Another student's name";
    }
}

如您所见,是“存储”柜台中的btn.Text一个使用它知道许多帖子已经完成。

您可以使用某种方式来存储输入的名称。我更喜欢将它保存在视图状态中,我可以用这段代码来做到这一点。

const string cArrNameConst = "cArr_cnst";

public string[] cArrKeepNames
{
    get
    {
        if (!(ViewState[cArrNameConst] is string[]))
        {
            // need to fix the memory and added to viewstate
            ViewState[cArrNameConst] = new string[5];
        }

        return (string[])ViewState[cArrNameConst];
    }
}

并且使用该代码,您可以在代码上从 0->4 添加任何名称,cArrKeepNames[]并在回发后拥有它,因为它保持在页面的视图状态。

protected void btnEnter_Click(object sender, EventArgs e)
{
    Button btn = (Button)sender;
    var Counter = Int32.Parse(btn.Text);

    // here you save the name in the array
    //  an magically is saved inside the page on viewstates data
    //  and you can have it anywhere on code behind.
    cArrKeepNames[Counter] = NameFromEditor.Text;

    Counter++;
    if(Counter >= 5)
    {   
        btn.Enable = false;
        Label1.Text = "No more studen's names please";
    }
    else
    {  
        btn.Text = Counter.ToString();

        Label1.Text = "Enter Another student's name";
    }
}

像这样的简单代码可以随时读取数组:

foreach (var One in cArrKeepNames)
    txtOutput.Text += "<br>" + One;

我对其进行了测试并且运行良好。

于 2012-09-09T20:05:23.360 回答