在dataGridView中更改列宽 - C#

时间:2013-05-25 15:03:37

标签: c# datagridview width

我想在datagridview中手动更改列宽。我该怎么办?我应该更改designer.cs中的代码还是只更改.cs?

我在代码中添加了一些内容,但它不起作用:

dataGridView1.Columns[0].Width = 200;

这是我的代码:

private void sqlConnResident()
        {
            BindingSource dbBindSource = new BindingSource();

            SqlCommand com;
            com = new SqlCommand();
            SqlConnection con = new SqlConnection(strCon);

            com.Connection = con;
            com.CommandType = CommandType.StoredProcedure;
            com.CommandText = "view_penghuni";

            SqlDataAdapter dataAdapter = new SqlDataAdapter(com);

            IDCabang = new SqlParameter();
            IDCabang.SqlDbType = SqlDbType.VarChar;
            IDCabang.Size = 5;
            IDCabang.ParameterName = "@IDCabang";
            IDCabang.Value = IDCabangC;
            IDCabang.Direction = ParameterDirection.Input;

            com.Parameters.Add(IDCabang);

            con.Open();

            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            dataAdapter.Fill(table);
            dbBindSource.DataSource = table;

            //dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
            // you can make it grid readonly.
            dataGridView1.ReadOnly = true;
            // finally bind the data to the grid
            dataGridView1.DataSource = dbBindSource;
            //this doesn't work
            dataGridView1.Columns[0].Width = 200;
            dataGridView1.Columns[1].Width = 200;

            con.Close();
        }

1 个答案:

答案 0 :(得分:6)

从代码中删除:

dataGridView1.Columns[0].Width = 200;
dataGridView1.Columns[1].Width = 200;

并添加到表单的构造函数:

Load += Form1_Load;

其中Form1_Load是:

private void Form1_Load(object sender, EventArgs e)
{
    dataGridView1.Columns[0].Width = 200;
    dataGridView1.Columns[1].Width = 200;
}