我有2列 代码背后我是这样的:
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = cs.getConnection();
string query = "SELECT ID , NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
GridViewCategory.DataSource = rdr;
GridViewCategory.DataBind();
GridViewCategory.Columns[0].HeaderText = "Header text"; // ERROR IS HERE
}
}
}
但这给了我一个错误:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
错误在这一行:GridViewCategory.Columns [0] .HeaderText =“Header text”;
答案 0 :(得分:0)
在将grid绑定到某个数据源之前,gridview中没有列。只需稍加改动就可以尝试使用代码
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = cs.getConnection();
string query = "SELECT ID , NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
GridViewCategory.DataSource = rdr;
GridViewCategory.DataBind();
// Write this line after above two
GridViewCategory.Columns[0].HeaderText = "Header text";
}
}
}
答案 1 :(得分:0)
在将数据分配给Columns [0]的代码中,由于尚未绑定GridView,因此没有Columns。重新排列代码的顺序:
using (SqlDataReader rdr = command.ExecuteReader())
{
GridViewCategory.DataSource = rdr;
GridViewCategory.DataBind();
If(GridViewCategory.Columns.Any())
GridViewCategory.Columns[0].HeaderText = "Header text";
}
答案 2 :(得分:0)
请试一试。
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = cs.getConnection();
string query = "SELECT ID , NAME FROM PROFITCATEGORIES";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
using (SqlDataReader rdr = command.ExecuteReader())
{
GridViewCategory.DataSource = rdr;
GridViewCategory.DataBind();
if (GridViewCategory.Rows.Count > 0)
{
GridViewCategory.HeaderRow.Cells[0].Text = "Header text";
}
}
}
}