我正在处理GridView中的ButtonField列,其RowCommand处理程序未在下一个生命周期中触发。
这是围绕网络的一个常见问题,并且 - 除其他外 - this SO帖子帮助我理解,它是由前者的控制树中的控件ID的差异和新的实例引起的网页。
剩下的内容:在Button_Click EventHandler中,在实例即将被销毁之前,我需要在gridView中保存(进入Session)ButtonField的ID,并将其传递给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?
答案 0 :(得分:0)
您需要在代码中更改一些内容以使其正常工作。 感谢你的努力。你快到了。
我使用ArrayList创建了一个示例工作解决方案。下载示例here 并根据您的需要进行修改。
<强> 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>
您可能还会考虑在标记上放置一个空的网格视图。这样可以省去您尝试手动创建网格的一些工作,并且您可以更轻松地连接事件处理程序。