开发者

Setting DropDown list width of DataGridView ComboBoxColumn - WinForms

开发者 https://www.devze.com 2023-01-19 06:58 出处:网络
I\'m having a datagridview with combobox column in it. This column is databound. I want to set the width of the dropdown list as per the largest item width in the list. For a normal combobox to achiev

I'm having a datagridview with combobox column in it. This column is databound. I want to set the width of the dropdown list as per the largest item width in the list. For a normal combobox to achieve the same I've used a extension method which will set the width of the combo box by finding the largest width item in the list. This is done in the DropDown event of the combobox.

Now in DataGridView combobox column I want to achieve the same. How can I开发者_运维知识库 get the DropDown event in this case? Please let me if there is any other way to achieve the same?


After little bit of investigation, I've found the answer for this.

I'm setting the datasource to the combobox column of the datagridview. So, after setting the datasource I'm finding the width of the largest item in the datatable for the value which is set as DisplayMember of the column. I'm using the same logic mentioned in the link given above in my question, instead of doing at DropDown event, I'm doing it while setting the Datasource, which is onetime. In the link given above in my question was setting the width of the drop down list every time drop down list is shown. So, in a way my approach looks good.

Here, how I done this:

// This line is picked up from designer file for reference
  DataGridViewComboBoxColumn CustomerColumn; 

  DataTable _customersDataTable = GetCustomers();

  CustomerColumn.DataSource = _customersDataTable;
  CustomerColumn.DisplayMember = Customer_Name;
  CustomerColumn.ValueMember = ID;

  var graphics = CreateGraphics();

  // Set width of the drop down list based on the largest item in the list
  CustomerColumn.DropDownWidth = (from width in
                         (from DataRow item in _customersDataTable.Rows
                          select Convert.ToInt32(graphics.MeasureString(item[Customer_Name].ToString(), Font).Width))
                       select width).Max();


You can try setting the AutoSizeMode of the column to AllCellsExceptHeader, or AllCells. You can also set the MinimumWidth of the column if auto-sizing it causes it to become too narrow.


You just need to set the DropDownWith property of your DataGridView column:

this.myColumnDataGridViewComboBoxColumn.DropDownWidth = variable;

For the variable, you can use a sql query to get the larger size of the column in your table.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号