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.