Method 1: manually add the able and then bind the datagridview
Datatable dt = new datatable (); // create a data table
DT. Columns. Add (New datacolumn ("ID", typeof (INT); // Add an int type column to the table
DT. Columns. Add (New datacolumn ("name", typeof (string); // Add a name column of the string type to the table.
Datarow Dr; // row
For (INT I = 0; I <3; I ++)
{
Dr = DT. newrow ();
Dr ["ID"] = I;
Dr ["name"] = "name" + I;
DT. Rows. Add (DR); // Add this row to the row of the object in the table.
}
Datagridview1.datasource = DT;
If you want to add a textbox effect column, you can do the following:
DT. Columns. Add (New datacolumn ("selected", typeof (bool ));
Method 2: insert data directly in the datagridview
Datagridview1.columncount = 4;
Maid = true;
// Set the column header style.
Datagridviewcellstyle columnheaderstyle = new datagridviewcellstyle ();
Columnheaderstyle. backcolor = color. Beige;
Columnheaderstyle. font = new font ("verdana", 10, fontstyle. Bold );
Datagridview1.columnheadersdefaultcellstyle = columnheaderstyle;
// Set the column header names.
Datagridview1.columns [0]. Name = "recipe ";
Datagridview1.columns [1]. Name = "category ";
Datagridview1.columns [2]. Name = "main ingredients ";
Datagridview1.columns [3]. Name = "rating ";
// Populate the rows.
String [] row1 =
New String [] {
"Meatloaf", "main dish ",
"Ground beef ",
"**"};
String [] row2 =
New String [] {
"Key lime pie", "dessert ",
"Lime juice, evaporated milk ",
"****"};
String [] row3 =
New String [] {
"Orange-Salsa pork chops", "main dish ",
"Pork chops, salsa, orange juice ",
"****"};
String [] row4 =
New String [] {
"Black Bean and rice salad", "salad ",
"Black beans, brown rice ",
"****"};
String [] row5 =
New String [] {
"Chocolate cheesecake", "dessert ",
"Cream cheese ",
"***"};
String [] row6 =
New String [] {
"Black bean dip", "appetizer ",
"Black beans, sour cream ",
"***"};
Object [] rows =
New object [] {row1, row2, row3, row4, row5, row6 };
Foreach (string [] rowarray
In rows)
{
Datagridview1.rows. Add (rowarray );
}
Insert the datagridviewcheckboxcolumn
Datagridviewcheckboxcolumn column = new datagridviewcheckboxcolumn ();
{
Column. headertext = "selected ";
Column. Name = isselected;
Column. autosizemode = maid;
Column. flatstyle = flatstyle. Standard;
Column. threestate = true;
Column. celltemplate = new maid ();
Column. celltemplate. style. backcolor = color. Beige;
}
Datagridview1.columns. insert (0, column );
Of course, other types of columns are similar.