如何在DataGridView中更改列宽?

时间:2012-08-12 23:01:36

标签: c# sql-server winforms sql-server-ce 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;
    }
}
}

3 个答案:

答案 0 :(得分:23)

您可以将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

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

答案 1 :(得分:3)

将“ 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

答案 2 :(得分:1)

在我的Visual Studio 2019中,只有在将AutoSizeColumnsMode属性设置为None之后,它才起作用。