1

Use a for loop to generate numbers, 1-100, and add each number to the dataGridView

After I tried with my code, I only showed one line, which is the last 100.

public void aaa(int i) {
    DataTable dt = new DataTable();
    dt.Columns.Add("host");

    DataRow dr = dt.NewRow();
    for (int a = 1; a <= i; a++)
    {
        dr[a] = i;
    }
    dt.Rows.Add(dr);

    this.dataGridView1.DataSource = dt;
}

private void button1_Click(object sender, EventArgs e) {
    for (int i = 1; i <= 254; i++)
    {
        aaa(i);
    }       
}
0

3 Answers 3

3

your btn_click function. Every loop will initialize or create a new object inside the aaa(i) function

Every time aaa(i) is called in the for loop DataTable dt = new DataTable() will be called

public void aaa(int i)
{
    DataTable dt = new DataTable(); ///this will initialize every time, a new data table will be created every loop
    dt.Columns.Add("host");

    DataRow dr = dt.NewRow();
    for (int a = 1; a <= i; a++)
    {
        dr[a] = i;
    }
        dt.Rows.Add(dr);

    this.dataGridView1.DataSource = dt;
}

}

Might i suggest you pass the 254 int in your aaa(i) function and do the loop inside like

private void button1_Click(object sender, EventArgs e)
{
   aaa(254);
}


public void aaa(int i) //value of i = 254
{
        DataTable dt = new DataTable();
        DataRow dr = dt.NewRow();
        for (var s = 0; s <= i; s++ ) {
            for (int a = 1; a <= i; a++)
            {
                dr[a] = i;
            }
                dt.Rows.Add(dr);

            this.dataGridView1.DataSource = dt;
        }
    }
}

or if the reason for the loop in the button is just for the number limit in the loop inside void aaa then you can simplify it as

public void aaa(int i) //value of i = 254
{
    DataTable dt = new DataTable();
    DataRow dr = dt.NewRow();
    for (int a = 1; a <= i; a++)
    {
        dr[a] = i;
    }
    dt.Rows.Add(dr);

    this.dataGridView1.DataSource = dt;
}

}

Sign up to request clarification or add additional context in comments.

Comments

1

I thought of the available solutions myself.

DataTable dt = new DataTable(); 
dt.Columns.Add("number"); 
int i = 10; 
int a = 0; 
while (a<=i) 
{ 
    DataRow dr = dt.NewRow(); 
    a++; 
    dr[0] = a; 
    dt.Rows.Add(dr);
 } 
this.dataGridView1.DataSource = dt;

Comments

0

I always do this like that

ListCollectionView collectionView;
collectionView = new ListCollectionView(*your list of items*);

datagridView1.ItemSource = collectionView;

Implementing like this give you in future open way for sorting, filtering etc. Here is link to ms documentation. where you will find more information about listCollectionView.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.