Reputation: 1154
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?
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();
}
Upvotes: 3
Views: 29415
Reputation: 1091
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_Load
is:
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns[0].Width = 200;
dataGridView1.Columns[1].Width = 200;
}
Upvotes: 7