简体   繁体   中英

Setting column width in Data grid view for my table

I am getting a error when I am trying to get a specific column from my table in the datagridview.

Here is how I populate the table----

public DataTable createGridForForm(int rows, int columns)
        {

            // Create the output table.
            DataTable table = new DataTable();


                   for (int i = 1; i <= columns; i++)
            {
                table.Columns.Add("column " + i.ToString());
            }


            for (int i = 1; i < rows; i++)
            {
                DataRow dr = table.NewRow();
                // populate data row with values here
                table.Rows.Add(dr);
            }    

            return table;
        }

And here is how i create the datagridview------

private void createGridInForm(int rows, int columns)
        {

            DataGridView RunTimeCreatedDataGridView = new DataGridView();
            RunTimeCreatedDataGridView.DataSource = createGridForForm(rows, columns);
            DataGridViewColumn ID_Column = RunTimeCreatedDataGridView.Columns[0];
        ID_Column.Width = 200;

            int positionForTable = getLocationForTable();
            RunTimeCreatedDataGridView.Size = new Size(800, 200);
            RunTimeCreatedDataGridView.Location = new Point(5, positionForTable);
            myTabPage.Controls.Add(RunTimeCreatedDataGridView);

        }

The error I am getting is that the Index was out of range. It may not be negative and must be smaller than the size. What I am trying to do is that I'm getting a table from a text file and then in run time I am showing it in my form, but the table doesn't match my data grid view in size, it doesn't look good. So I want to make the table fit the Data grid view.

Try-

DataGridViewColumn ID_Column = dataGridView1.Columns[0];
ID_Column.Width = 200;

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