3

我想在 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();
        }
4

1 回答 1

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;
}
于 2013-05-25T15:34:38.990 回答