修改dataGridView的列宽度
本文关键字:dataGridView 修改 | 更新日期: 2023-09-27 18:15:34
我想在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();
}
从代码中删除:
dataGridView1.Columns[0].Width = 200;
dataGridView1.Columns[1].Width = 200;
并添加到Form的构造函数中:
Load += Form1_Load;
其中Form1_Load
为:
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns[0].Width = 200;
dataGridView1.Columns[1].Width = 200;
}