简体   繁体   中英

Variable as Length in for Loop?

I have a problem with defining the length in my for loop. I'm counting rows in a table from a SQL database and want this number to be the length of the for loop.

This is the code for the for loop:

    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);
        }

    }

And this is the code that counts the rows in my database table.

    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();
            }
        }
    }

I want to use this to show info on every ship that is in my database by creating divs in my for loop.

Can anyone help me with how I need to define the length?

Thanks!

Do not call your A method inside the condition of the for loop - it will be executed on every iteration.

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

public int A()
{
  ...
  using ( ...
    using ( ...
    {
      ...
      return count;
    }
}

In this case, simply make A() return int instead of void :

public int A() {
    int count = 0;
    //do db stuff
    return count;
}

Then in your loop:

int shipCount = A();

for (int i = 0; i < shipCount; i++) {
    //make div
}

Too many things to say ^^' First if you need to display info of the element in your table AlgSchipInfo, just select these data an after you will have the count in the datatable or anything else like an ORM.

When you get your datatable from the DB, bind it to a repeator or another compenent to list your items. It will bee more efficient than do it from scratch IMAO.

If you have more specific question you're welcome ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM