更改 dataGridView 中的列宽 - C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16750826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change column width in dataGridView - C#
提问by noobprogrammer
I want to change the column width manually in a datagridview. What should I do? Should I change the code in designer.cs or just in .cs?
我想在 datagridview 中手动更改列宽。我该怎么办?我应该更改designer.cs 中的代码还是只更改.cs 中的代码?
I have added something in the code but it doesn't work:
我在代码中添加了一些东西,但它不起作用:
dataGridView1.Columns[0].Width = 200;
Here's my code:
这是我的代码:
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();
}
采纳答案by Rafal
Remove from your code:
从您的代码中删除:
dataGridView1.Columns[0].Width = 200;
dataGridView1.Columns[1].Width = 200;
and add to constructor of your Form:
并添加到您的表单的构造函数中:
Load += Form1_Load;
where Form1_Loadis:
在哪里Form1_Load:
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns[0].Width = 200;
dataGridView1.Columns[1].Width = 200;
}

