简体   繁体   中英

How do i add more cells to a column of datagridview?

数据网格视图

Now i have one cell i added it in the designer but if i want to add more cells in my code ?

I tried in the constructor to do:

DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
row.Cells[0].Value = "XYZ";
row.Cells[1].Value = 50.2;
dataGridView1.Rows.Add(row);

But getting exception on:

row.Cells[1].Value = 50.2;

Index was out of range. Must be non-negative and less than the size of the collection

Yes you should get an exception. Look at your code below. With row.Cells[1] you are actually referring to 2nd column in your gridview which apparently doesn't exists and so the end result.

 row.Cells[1].Value = 50.2;

If you want to have another column to your grid then either add that using your designer surface (OR) create a DataTable with required columns and set that to DataSource of your gridview.

How to create a DataTable and attach it to GridView?

Search Google

EDIT:

In case you are still struggling understanding my comment then this is what I meant to say (sample code)

    public Form1()
    {
        InitializeComponent();

        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("Message Subject");
        dt.Columns.Add(dc);

        DataRow dr = dt.NewRow();
        dr[dc] = "test";

        DataRow dr1 = dt.NewRow();
        dr1[dc] = "test123";

        dt.Rows.Add(dr);
        dt.Rows.Add(dr1);

        this.dataGridView1.DataSource = dt;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM