如何在C#数据网格视图中将文本添加到行标题中
本文关键字:文本 添加 标题 视图 数据 网格 数据网 | 更新日期: 2023-09-27 18:26:04
这里有很多关于这个问题的问题,但我已经尝试了发布的解决方案,但仍然没有成功。
我有一个数据网格视图,我想在其中显示行标题上的行号。这就是我尝试过的:
gridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
gridView.AutoResizeRowHeadersWidth(
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
foreach (DataGridViewRow row in gridView.Rows)
{
row.HeaderCell.Value = (row.Index + 1).ToString();
}
这段代码是从OnLoad事件中调用的,因为在其他问题中,它指出代码不应该在构造函数中运行。
建议?谢谢
我认为我的方法是在ItemDataBound事件上绑定一行,而不是在一个地方遍历这些行。大致如下:
/// <summary>
/// Which row is currently being rendered
/// </summary>
protected int RowIndex { get; set; }
protected override void OnLoad(EventArgs e)
{
this.RowIndex = 0;
this.DataGrid.DataSource = new string[] { "a", "b", "c" }; // bind the contents
this.DataGrid.DataBind();
}
/// <summary>
/// When an item is bound
/// </summary>
protected void OnItemDataBound(object sender, DataGridItemEventArgs e)
{
this.RowIndex++;
Label label = e.Item.FindControl("RowLabel") as Label;
if (label != null)
{
label.Text = this.RowIndex.ToString();
}
}
使用网格视图,如果这是Header行,您可以在OnRowDataBound事件中检测到:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
Label label = e.Row.FindControl("RowLabel") as Label;
label.Text = "the text i want";
}
}
当网格数据绑定时激发此事件。它将为绑定的每一行数据以及页眉和页脚行激发。
因此,您很可能会在Page_Load事件期间调用DataGridView1.Databind(),这将多次触发OnRowDataBound事件。