[英]How can I add text to my rowheaders in a datagridview, C#?
There are many questions concerning this issue here, but I have tried the solutions posted and still don't get it to work. 这里有很多与此问题有关的问题,但是我尝试过发布的解决方案,但仍然无法正常工作。
I have a datagridview where I want to show the rownumber on the row headers. 我有一个datagridview,我想在行标题上显示行号。 This is what I have tried:
这是我尝试过的:
gridView.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToDisplayedHeaders;
gridView.AutoResizeRowHeadersWidth(
DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
foreach (DataGridViewRow row in gridView.Rows)
{
row.HeaderCell.Value = (row.Index + 1).ToString();
}
This code is called from the OnLoad event, since in other questions it is stated that the code should not be run in the constructor. 该代码是从OnLoad事件中调用的,因为在其他问题中,该代码不应在构造函数中运行。
Advice? 忠告? Thanks!
谢谢!
I think my approach would be to bind a row on the ItemDataBound event rather than going over the rows all a single place. 我认为我的方法是在ItemDataBound事件上绑定一行,而不是将行全部都放在一个地方。 Something along the lines of:
类似于以下内容:
/// <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();
}
}
using a grid view you can detect in the OnRowDataBound event if this is the Header row like so: 使用网格视图,您可以在OnRowDataBound事件中检测到这是否是Header行,如下所示:
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";
}
}
This event fires when the grid databinds. 网格数据绑定时将触发此事件。 It will fire for every row of data that is bound as well as the header and footer rows.
它将为绑定的每一行数据以及页眉和页脚行触发。
SO you will call DataGridView1.Databind() during the Page_Load event most probably and this will trigger the OnRowDataBound event multiple times. 因此,您很有可能在Page_Load事件期间调用DataGridView1.Databind(),这将多次触发OnRowDataBound事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.