我正在尝试以编程方式添加一个按钮ASP.NET
作为C#
后端。我能够显示该按钮,但是当用户单击该按钮时,不会触发 RowCommand。
我相信问题是我在用户单击“提交”按钮后创建按钮。如果我在 page_load 中创建按钮,那么 RowCommand 可以工作。
这是网站应该如何流动:
- 页面加载:显示基本数据。
- 用户单击创建一个 的提交按钮,该按钮
GridView
具有一个ButtonField
。theGridView
和ButtonField
get 都是在后端动态创建的。 - 用户然后单击生成的按钮,它应该触发
RowCommand
这是代码:
Page_load
protected void Page_Load(object sender, EventArgs e)
{
//Nothing because we only want to create the button after the user
//clicks on submit
}
randomGridView
生成 Gridview 和按钮
public void randomGridView(Table t, int x)
{
GridView gv1 = new GridView();
GridView gv2 = new GridView();
GridView gv3 = new GridView();
GridView gv4 = new GridView();
TableRow r = new TableRow();
for (int i = 0; i < x; i++)
{
TableCell c = new TableCell();
c.BorderStyle = BorderStyle.Solid;
if (i == 0)
{
c.Controls.Add(gv1);
}
if (i == 1)
{
c.Controls.Add(gv2);
}
if (i == 2)
{
c.Controls.Add(gv3);
}
if (i == 3)
{
c.Controls.Add(gv4);
}
r.Cells.Add(c);
}
t.Rows.Add(r);
//Where the xml gets bonded to the data grid
XmlDataSource xds = new XmlDataSource();
xds.Data = xml;
xds.DataBind();
xds.EnableCaching = false;
gv1.DataSource = xds;
ButtonField temp = new ButtonField();
temp.ButtonType = ButtonType.Image;
temp.ImageUrl = "~/checkdailyinventory.bmp";
temp.CommandName = "buttonClicked";
temp.HeaderText = " ";
gv1.Columns.Add(temp);
gv1.RowCommand += new GridViewCommandEventHandler(CustomersGridView_RowCommand);
gv1.RowDataBound += new GridViewRowEventHandler(inventoryGridView_RowDataBound);
gv1.DataBind();
xds.Data = xml;
xds.DataBind();
xds.EnableCaching = false;
gv2.DataSource = xds;
gv2.DataBind();
xds.Data = xml;
xds.DataBind();
xds.EnableCaching = false;
gv3.DataSource = xds;
gv3.DataBind();
xds.Data = xml;
xds.DataBind();
xds.EnableCaching = false;
gv4.DataSource = xds;
gv4.DataBind();
}
inventoryGridView_RowDataBound
我尝试在第一个单元格中手动添加一个按钮
public void inventoryGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
Button temp = new Button();
temp.CommandName = "buttonClicked";
temp.Text = "temp button!";
e.Row.Cells[0].Controls.Add(temp);
}
CustomersGridView_RowCommand
这是需要被解雇的
public void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "buttonClicked")
{
int index = Convert.ToInt32(e.CommandArgument);
Label1.Text = index.ToString();
}
}
Button1_Click
什么实际创建了网格视图和按钮
public void Button1_Click(object sender, EventArgs e)
{
randomGridView(Table1, 1);
randomGridView(Table2, 4);
}
那么如何让按钮触发CustomersGridView_RowCommand
呢?还是无法链接动态生成的按钮?
编辑:这是 ASPX 页面:
<table>
<tr>
<td>
<div id="div1" style="width: 257px; height: 500px; overflow-x: scroll; overflow-y: hidden;">
<asp:Table ID="Table1" runat="server">
</asp:Table>
</div>
</td>
<td>
<div id="div2" style="width: 500px; height: 500px; overflow: scroll;">
<asp:Table ID="Table2" runat="server">
</asp:Table>
</div>
</td>
</tr>
</table>