tag:blogger.com,1999:blog-4144465122629949728.post-80934722823240245402008-05-09T10:56:00.000-04:002008-05-09T11:00:54.703-04:00Setting datagridview programmatically and tuning column widths<div class=Section1> <p class=MsoNormal>I’m working on an application right now that require datagridviews to be built programmatically instead of using the designer. Some of these datagridviews have a large number of columns and it’s a painful trial and error method to get the width right. To simplify the process I added a bit of temporary code to the class where the datagridview lived. The code basically fires the ColumnWidthChanged event of the datagridview and then displays the width in a messagebox. I know it’s not fancy, but its temporary and it makes life very simple when you have to configure widths for a bunch of columns. All you have to do is add this code, run the program to populate the datagridview with data and tune the width till your happy and note the width. Then you can reset it in code to the final widths.<o:p></o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal>Here’s the code:<o:p></o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal>Add to your class constructor:<o:p></o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal>this.<datagridviewname>.ColumnWidthChanged += new DataGridViewColumnEventHandler(mydgrid_ColumnWidthChanged);<o:p></o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal>Add the event handler code to the class:<o:p></o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal>Void mydgrid_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)<o:p></o:p></p> <p class=MsoNormal>{<o:p></o:p></p> <p class=MsoNormal> MessageBox.Show(e.Column.Width.ToString());<o:p></o:p></p> <p class=MsoNormal>}<o:p></o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal><o:p> </o:p></p> <p class=MsoNormal>When your all finished just delete or comment out the event and eventhandler.<o:p></o:p></p> </div> Garyhttp://www.blogger.com/profile/04366610632368791421noreply@blogger.com