0

I have a DataGridView with data I extract from SQL Server. I never know how many records i'll have in it so I need the grid to be variable to the number of rows extracted.

Exemple :

enter image description here

  • Picture 1 : What I have right now. 1 row was extracted so I have a big dark gray space where the could have been data.
  • Picture 2 : What I want to have with only 1 row extracted. The grid resizes automaticly depending on the number of rows.
  • Picture 3 : What I would like to have with many rows.

Also, I would like to remove the empty row that is always added too, adding a new row won't be an option.

Is that possible ?

phadaphunk
  • 12,785
  • 15
  • 73
  • 107

2 Answers2

1

You are looking for DataSet.Datatable.Rows.Count this will tell you the total rows returned from your Sql Server

Update this cannot be achieved by using the any properties of the DataGridView Control

HatSoft
  • 11,077
  • 3
  • 28
  • 43
  • What do I do with number ofr rows when I get them ? How can I tell that if I have 6 rows show me only 6 rows not 6 rows + a big gray space ? Thanks in advance – phadaphunk Jul 23 '12 at 16:23
  • @PhaDaPhunk looks like this question have been asked before and their is no solution on the control itself, please look at this post http://stackoverflow.com/questions/2162756/datagridview-remove-unused-space – HatSoft Jul 23 '12 at 16:53
  • Thanks a lot I'll stop looking for a way to do it then. – phadaphunk Jul 23 '12 at 16:56
0

You need to set the AutoSizeColumns properties:

datagridview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
datagridview.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);

Assuming you're filling the grid from a DataSet, you can use this to prevent empty rows from being added:

foreach (DataRow row in dataset.Tables[0].Rows)
{
      if (!string.IsNullOrWhiteSpace(row[0].ToString()))
      {
            //add row
      }
}
dtsg
  • 4,408
  • 4
  • 30
  • 40
  • I'm using a DataTable as a DataSource. I changed both Porperties but I still get the big grey space... – phadaphunk Jul 23 '12 at 16:22
  • Where did you place the code to set those properties? You will get a gray area at the bottom of the grid until your query returns enough results to fill it... Otherwise you could just adjust it's height? – dtsg Jul 23 '12 at 16:24
  • Yes I know that's why i'm asking this question. Is there a way NOT to wait for enough rows and make the Height Variable instead.. I didn't code it I changed those properties in the designer property pannel – phadaphunk Jul 23 '12 at 16:29