以编程方式添加按钮列

3
我将尝试通过编程的方式向GridView添加一个ButtonField
因此,在aspx中,它看起来像这样:
<asp:ButtonField ButtonType="Image" 
                 CommandName="buttonClicked" 
                 ImageUrl="~/checkdailyinventory.bmp" />

这是我在C#中尝试复制的内容。

 GridView genGridView = new GridView();

        //Where the xml gets bonded to the data grind
        XmlDataSource xds = new XmlDataSource();
        xds.Data = xml;
        xds.DataBind();
        xds.EnableCaching = false;


        genGridView.DataSource = xds;
        genGridView.DataBind();


        // formating is done here

        ButtonField test3 = new ButtonField();
        test3.ButtonType = ButtonType.Image;
        test3.CommandName = "buttonClicked";
        test3.ImageUrl = "~/checkdailyinventory.bmp";
        genGridView.Columns.Add(test3);

这不会创建任何新的列。

希望能获得任何帮助。

更新进度

我已经成功创建了列,但它们是第一列,而不是最后一列。为了做到这一点,我必须在数据绑定之前放置按钮创建和添加列。

GridView genGridView = new GridView();

        //Where the xml gets bonded to the data grind
        XmlDataSource xds = new XmlDataSource();
        xds.Data = xml;
        xds.DataBind();
        xds.EnableCaching = false;

        //Set the rowdatabound before binding.  This will allow the correct function to be called.
        genGridView.RowDataBound += new GridViewRowEventHandler(inventoryGridView_RowDataBound);
        genGridView.RowCommand += new GridViewCommandEventHandler(inventoryGridView_RowCommand);

        ButtonField test3 = new ButtonField();
        test3.ButtonType = ButtonType.Image;
        test3.CommandName = "buttonClicked";
        test3.ImageUrl = "checkdailyinventory.bmp";

        genGridView.Columns.Add(test3);
        genGridView.DataSource = xds;
        genGridView.DataBind();

而实际上,你的html可能是这个样子:

所以它不能正常工作。 请确保使用正确的html代码。

<td><input type="image" src="checkdailyinventory.bmp" onclick="javascript:__doPostBack('inventoryGridView','buttonClicked$2')" style="border-width:0px;" /></..>

然而实际上,它看起来是这样的:

<td><input type="image" src="checkdailyinventory.bmp" onclick="javascript:__doPostBack('ctl03','buttonClicked$2')" style="border-width:0px;" /></..>

因此,我需要找出如何将ct103替换为inventoryGridView


为什么不使用DataGridView组件? - Martin Ch
我对asp.net和c#相对较新,所以我还没有真正能够使其正常工作。 - user1301708
以上代码在哪里运行?是在Page_Load中吗? - benni_mac_b
代码正在页面加载时运行。虽然它必须经过几个函数才能最终创建表格。 - user1301708
1个回答

0

看起来你正在代码后台创建genGridView,但没有将其添加到页面中。

我猜GridView在标记中定义。如果是这样,请尝试删除该行。

GridView genGridView = new GridView(); 

你应该能够将你的列添加到页面上的对象中。

提示:你可能需要在OnInit(或从OnInit调用的方法)中添加该项。


网格视图是通过编程方式创建的。因此,我正在生成一堆GridView,然后将它们全部放入自己的单元格中。然后,我将它们放入一行中,再将该行添加到我定义的asp:table中。 - user1301708
所以GridView已经显示在页面上了,但是按钮没有显示,或者连GridView都没有显示?此外,您在添加到页面上的表格中是否有ContentPlaceHolder? - Dan Norton
网格视图已经加载到页面,但是按钮没有显示出来。由于我使用asp:table来显示所有网格视图,因此我没有ContentPlaceHolder。 <div id="div2" style="height: 500px; width: 300px; overflow: scroll;" onscroll="OnScroll2(this)"> <asp:Table ID="Table2" runat="server"> </asp:Table> </div> </td> - user1301708

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接