变量为循环中的长度?

Ric*_*wer 0 c# for-loop

我在for循环中定义长度时遇到问题.我正在计算SQL数据库中表中的行,并希望这个数字是for循环的长度.

这是for循环的代码:

    protected void Page_Load(object sender, EventArgs e)
    {

        for (int i = 0; i < A; i++)
        {
            System.Web.UI.HtmlControls.HtmlGenericControl createDiv =
            new System.Web.UI.HtmlControls.HtmlGenericControl("DIV");
            createDiv.ID = "createDiv";
            this.Controls.Add(createDiv);
        }

    }
Run Code Online (Sandbox Code Playgroud)

这是计算数据库表中行数的代码.

    public void A()
    {
        string stmt = "SELECT COUNT(*) FROM AlgSchipInfo";
        int count = 0;

        using (SqlConnection thisConnection = new SqlConnection ("DataSource=VMB-LP12;Initial Catalog=SmmsData;Integrated Security=True"))
        {
            using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
            {
                thisConnection.Open();
                count = (int)cmdCount.ExecuteScalar();
                TextBox2.Text = count.ToString();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想通过在for循环中创建div来使用它来显示我数据库中每艘船的信息.

任何人都可以帮助我如何定义长度?

谢谢!

Igo*_*gor 5

不要Afor循环条件内调用您的方法- 它将在每次迭代时执行.

int count = A();
for (int i = 0; i < count; i++)
{
  System.Web.UI.HtmlControls.HtmlGenericControl createDiv = ...
}

public int A()
{
  ...
  using ( ...
    using ( ...
    {
      ...
      return count;
    }
}
Run Code Online (Sandbox Code Playgroud)