Datagridview dynamically add columns and rows, and refresh after addition

Source: Internet
Author: User

Sometimes you need to dynamically Add the column name of the datagridview:

System. windows. forms. datagridviewtextboxcolumn [] column = new datagridviewtextboxcolumn [columnnum]; for (INT I = 0; I <columnnum; I ++) {column [I] = new datagridviewtextboxcolumn ();} column [0]. headertext = "Ticket No."; column [0]. name = "Ticket No."; column [0]. readonly = true; column [0]. defaultcellstyle. backcolor = color. lightsteelblue; column [0]. readonly = true; column [1]. headertext = "sample number"; column [1]. name = "sample number"; Int J = 2; foreach (datarow row in DT. rows) {If (j <columnnum) {column [J]. headertext = row ["qcitem_name"]. tostring (); column [J]. name = row ["qcitem_name"]. tostring (); j ++ ;}} this. dgv. columns. addrange (column); this. resumelayout (false );

When dynamically adding rows and columns, do not assign datasource to the datagridview. If you assign a value to a able directly, problems may occur.

You also need to dynamically convert the datatable to add data row by row.

      if (oldRowNum > 0)            {                foreach (DataRow row in ddt.Rows)                {                    object[] Array = new object[columnNum];                    for (int i = 0; i < columnNum; i++)                    {                        Array[i] = row[i];                    }                    dgv.Rows.Add(Array);                }            }

Another key point is to refresh the data after dynamically adding columns to the datagridview and clear all contents of the datagridview.

     dgv.Columns.Clear();

After the data is cleared, add the result of the able statement row by row.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.