c# dataGridView for 循环添加数据

使用for循环生成数字1-100,并将每个数字添加到dataGridView


在我尝试使用代码后,我只显示了一行,即最后 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);

    }       

}


一只萌萌小番薯
浏览 308回答 3
3回答

青春有我

你的btn_click职能。aaa(i)每个循环都会在函数内初始化或创建一个新对象每次aaa(i)在for循环中调用DataTable dt = new DataTable()都会被调用public void aaa(int i){&nbsp; &nbsp; DataTable dt = new DataTable(); ///this will initialize every time, a new data table will be created every loop&nbsp; &nbsp; dt.Columns.Add("host");&nbsp; &nbsp; DataRow dr = dt.NewRow();&nbsp; &nbsp; for (int a = 1; a <= i; a++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; dr[a] = i;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; dt.Rows.Add(dr);&nbsp; &nbsp; this.dataGridView1.DataSource = dt;}}254我是否可以建议您在函数中传递intaaa(i)并在内部执行循环,例如private void button1_Click(object sender, EventArgs e){&nbsp; &nbsp;aaa(254);}public void aaa(int i) //value of i = 254{&nbsp; &nbsp; &nbsp; &nbsp; DataTable dt = new DataTable();&nbsp; &nbsp; &nbsp; &nbsp; DataRow dr = dt.NewRow();&nbsp; &nbsp; &nbsp; &nbsp; for (var s = 0; s <= i; s++ ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int a = 1; a <= i; a++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dr[a] = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dt.Rows.Add(dr);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.dataGridView1.DataSource = dt;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}或者,如果按钮中循环的原因只是因为 void 内循环的数量限制,aaa那么您可以将其简化为public void aaa(int i) //value of i = 254{&nbsp; &nbsp; DataTable dt = new DataTable();&nbsp; &nbsp; DataRow dr = dt.NewRow();&nbsp; &nbsp; for (int a = 1; a <= i; a++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; dr[a] = i;&nbsp; &nbsp; }&nbsp; &nbsp; dt.Rows.Add(dr);&nbsp; &nbsp; this.dataGridView1.DataSource = dt;}}

浮云间

我自己想到了可用的解决方案。DataTable&nbsp;dt&nbsp;=&nbsp;new&nbsp;DataTable();&nbsp; dt.Columns.Add("number");&nbsp; int&nbsp;i&nbsp;=&nbsp;10;&nbsp; int&nbsp;a&nbsp;=&nbsp;0;&nbsp; while&nbsp;(a<=i)&nbsp; {&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;DataRow&nbsp;dr&nbsp;=&nbsp;dt.NewRow();&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;a++;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;dr[0]&nbsp;=&nbsp;a;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;dt.Rows.Add(dr); &nbsp;}&nbsp; this.dataGridView1.DataSource&nbsp;=&nbsp;dt;

翻阅古今

我总是这样做ListCollectionView collectionView;collectionView = new ListCollectionView(*your list of items*);datagridView1.ItemSource = collectionView;这样的实现为您提供了未来开放的排序、过滤等方式。
打开App,查看更多内容
随时随地看视频慕课网APP