2

I have dynamically created Datagrid , however I need to adjust width of columns, like I have Itemname its width should be 150 quantity should be 50 and so on. Heres my code for dynamic datagrid :

           dtitem = loadbl.itemonkot(dt.Rows[0][2].ToString());
            DataGrid dgv = new DataGrid();
            dgv.Location = new Point(3, 48);
            dgv.Width = 302;
            dgv.Height = 223;
            dgv.RowHeadersVisible = false;
            dgv.Font = new System.Drawing.Font("Microsoft Sans Serif", 10);
            dgv.DataSource = dtitem;
            grpbx.Controls.Add(dgv);
            grpbx.Name = "order";
            grpbx.Text = "Order";
            grpbx.Width = 311;
            grpbx.Height = 322;
            grpbx.Location = new Point(12, 12);

I tried google it said Here :

DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;

How do I set to my datagrid ie; dgv

Please help, Thanks

mark
  • 623
  • 3
  • 21
  • 54

2 Answers2

1

Have you tried something like:

DataGridView dgv = new DataGridView();
...
dgv.Columns[0].Width = 150;
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • i dont get _.Columns_ in dgv – mark Oct 31 '15 at 08:08
  • That's because you've got a DataGrid not a DataGridVIEW – Jeremy Thompson Oct 31 '15 at 08:12
  • I tried both DataGrid and DataGridVIEW but no such .Columns – mark Oct 31 '15 at 10:21
  • Can you show me how you hold a reference to dgv in a private member variable (or searching for it in the forms control collection) and setting the columns width? I don't think columns is coming up in intellisense because the control is not in scope/accessible – Jeremy Thompson Oct 31 '15 at 10:36
  • I am sorry ,, it did work had to reopen VS2012, `DataGridView dgv = new DataGridView(); dgv.Columns[0].Width = 150; ` however now I am getting **Index was out of range. Must be non-negative and less than the size of the collection.** – mark Oct 31 '15 at 10:44
  • Just check the grid has data and in a button click or something where you can see the grid has been populated try and set column widths to work out what going on, having to restart vs2012 doesn't sound like a good sign – Jeremy Thompson Oct 31 '15 at 10:50
  • I have values in grid if i dont use width works fine. Is that what you are asking? – mark Oct 31 '15 at 11:42
  • 1
    I think you should re-post your code. The error you are getting is saying you don't have any columns added to the `DataGridView` at the time you are trying to set the width. You must set the columns widths after the data source has been set and/or the columns are created. – jaredbaszler Nov 04 '15 at 18:30
1

An alternative is to auto size the columns after you populate the data. With:

dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

jaredbaszler
  • 3,941
  • 2
  • 32
  • 40