我正在处理GridView中的ButtonField列,该列的RowCommand处理程序不会在以下生命周期中触发。
这是Web上的一个常见问题,除其他外,此SO帖子帮助我了解到,这是由网页的旧实例和新实例的控件树中控件ID的不同引起的。
剩下的事情:在Button_Click EventHandler中,在实例将被销毁之前,我需要将gridField的ButtonField的ID保存(存入Session中),然后将其传递给EventHandler,如下所示:
protected GridView Create_GV(DataTable BetTable)
{
GridView GV = new GridView
{
DataSource = BetTable,
HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center
};
GV.Columns.Add(new ButtonField { Text = "+", CommandName = "Select" });
GV.DataBind();
GV.RowCommand += GV_RowCommand;
//cycle the columns so that the buttonfield is the last one
int ncol = BetTable.Columns.Count;
for (int i = 0; i < ncol; i++) GV.HeaderRow.Cells[i].Text = GV.HeaderRow.Cells[i + 1].Text;
GV.HeaderRow.Cells[ncol].Text = "Přidat";
foreach (GridViewRow row in GV.Rows)
{
List<TableCell> columns = new List<TableCell>();
foreach (DataControlField column in GV.Columns)
{
TableCell cell = row.Cells[0];
row.Cells.Remove(cell);
columns.Add(cell);
}
row.Cells.AddRange(columns.ToArray());
}
return GV;
}
然后在Page_Init中,我需要重新创建GridView,并将ButtonField的ID重置为原始值。
我故意说出ButtonField的ID,因为我什至不知道是否存在一个或多个-无法找到。
如何获取/设置GridView的ButtonField ID?
您需要在代码中进行一些更改才能使它们正常工作。尝试的荣誉。你快到了。
我使用ArrayList创建了一个示例工作解决方案。在此处下载示例并对其进行修改以适合您的需求。
Aspx.cs
using System.Collections.Generic;
namespace WebApplication3
{
public partial class WebForm1 : System.Web.UI.Page
{
GridView GV = null;
protected void Page_Load(object sender, EventArgs e)
{
//Dummy datasource
ArrayList names = new ArrayList() { };
names.Add(new Person { Age = 29, Name = "Abide", Surname = "Masaraure" });
names.Add(new Person { Age = 28, Name = "Lopi", Surname = "Sewa" });
Create_GV(names);
}
protected void Create_GV(ArrayList BetTable)
{
if (GV == null)
{
GV = new GridView
{
DataSource = BetTable,
HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center
};
GV.DataSource = BetTable;
GV.Columns.Add(new ButtonField { Text = "+", CommandName = "Select" });
GV.RowCommand += GV_RowCommand;
GV.RowCreated += GV_RowCreated;
GV.DataBind();
GV.HeaderRow.Cells[BetTable.Capacity-1].Text = "Přidat";
form1.Controls.Add(GV);
}
}
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
//this will fire
}
protected void GV_RowCreated(object sender, GridViewRowEventArgs e)
{
GridViewRow row = e.Row;
// Intitialize TableCell list
List<TableCell> columns = new List<TableCell>();
foreach (DataControlField column in GV.Columns)
{
//Get the first Cell /Column
TableCell cell = row.Cells[0];
// Then Remove it after
row.Cells.Remove(cell);
//And Add it to the List Collections
columns.Add(cell);
}
// Add cells
row.Cells.AddRange(columns.ToArray());
}
}
class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
}
}
标记
<html>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
您可能还考虑在标记上放置一个空的网格视图,这将节省您尝试手动创建网格的工作量,并且使连接事件处理程序更加容易。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句