Как изменить ширину столбца в DataGridView?
Я создал базу данных и таблицу с использованием Visual Studio SQL Server Compact 3.5 с набором данных в качестве источника данных. На моем WinForm у меня есть DataGridView с 3 столбцами. Однако я не смог понять, как заставить столбцы занимать всю ширину DataGridView, как показано на рисунке ниже.
Я хочу сделать столбец сокращений более широким, а затем расширить столбец описания до самого края формы. Какие-либо предложения?
Обновить:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace QuickNote
{
public partial class hyperTextForm : Form
{
private static hyperTextForm instance;
public hyperTextForm()
{
InitializeComponent();
this.WindowState = FormWindowState.Normal;
this.MdiParent = Application.OpenForms.OfType<Form1>().First();
}
public static hyperTextForm GetInstance()
{
if (instance == null || instance.IsDisposed)
{
instance = new hyperTextForm();
}
return instance;
}
private void abbreviationsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.abbreviationsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.keywordDBDataSet);
}
private void hyperTextForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'keywordDBDataSet.abbreviations' table. You can move, or remove it, as needed.
this.abbreviationsTableAdapter.Fill(this.keywordDBDataSet.abbreviations);
abbreviationsDataGridView.Columns[1].Width = 60;
abbreviationsDataGridView.Columns[2].Width = abbreviationsDataGridView.Width - abbreviationsDataGridView.Columns[0].Width - abbreviationsDataGridView.Columns[1].Width - 72;
}
}
}
2 ответа
Вы можете установить ширину столбца abbrev на фиксированную ширину в пикселях, а затем установить ширину столбца описания на ширину DataGridView, минус сумма значений ширины других столбцов и некоторого дополнительного поля (если вы хотите предотвратить горизонтальная полоса прокрутки от появления в DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
Если вы хотите, чтобы столбец описания всегда занимал "остаток" от ширины DataGridView, вы можете поместить что-то вроде приведенного выше кода в Resize
обработчик события DataGridView.
Установите для свойства "AutoSizeColumnsMode" значение "Заполнить". По умолчанию установлено значение "НЕТ". Теперь столбцы будут заполнены через DatagridView. Затем вы можете установить ширину других столбцов соответственно.
DataGridView1.Columns[0].Width=100;// The id column
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining
//space
В моей Visual Studio 2019 это сработало только после того, как я установил AutoSizeColumnsMode
собственность None
.