如何在DataGridView中更改列宽?

tyl*_*hes 15 c# sql-server sql-server-ce winforms compact-database

我使用Visual Studio的SQL Server Compact 3.5创建了一个数据库和表,数据集作为我的数据源.在我的WinForm上,我有一个包含3列的DataGridView.但是,我一直无法弄清楚如何使列占据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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

hmq*_*esy 24

您可以将abbrev列的宽度设置为固定的像素宽度,然后将description列的宽度设置为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
Run Code Online (Sandbox Code Playgroud)

如果您希望描述列始终占用DataGridView宽度的"余数",则可以将类似上述代码的内容放在ResizeDataGridView 的事件处理程序中.

  • 您的DataGridView是否将"AutoSizeColumnsMode"属性设置为"None"以外的其他属性?这会阻止您的代码设置列宽. (2认同)

小智 5

将“AutoSizeColumnsMode”属性设置为“Fill”。默认设置为“NONE”。现在将在 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
Run Code Online (Sandbox Code Playgroud)