[英]How to Change the Header Name / Column Name Of a Datatable Fed to dataGridView
[英]How we change datagridview header name?
我在Windows窗体应用程序中编写了用于更改标头名称的代码。
DataGridViewCellStyle columnHeaderStyle = new DataGridViewCellStyle();
columnHeaderStyle.BackColor = Color.Beige;
columnHeaderStyle.Font = new Font("Bookman Old Style", 8, FontStyle.Bold);
dataGridView1.ColumnHeadersDefaultCellStyle = columnHeaderStyle;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
dataGridView1.Columns[0].HeaderText = "Item Code";
dataGridView1.Columns[1].HeaderText = "Item Name";
但是,当我运行此代码时,显示错误。 “ Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
”我该如何解决?
索引超出范围。 必须为非负且小于集合的大小参数名称:index
您收到此错误,因为您的datagridview没有任何列,并且您尝试在以下代码中访问索引0处的列
dataGridView1.Columns[0]
当我浏览您的评论时,您已经提到您创建了一个空的datagridview,然后为其分配数据源 。 如果是这种情况,则需要在分配数据源之后访问列。 您还需要确保autogeneratecolumns = true
或者,如果您要创建未绑定的DataGridView ,下面的代码示例演示如何创建未绑定的DataGridView ;或者
虽然是为了避免异常并确保datagridview中有列。 你可以先做
if(dataGridView1.Columns.Count> 2)
{
//your code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.