【问题标题】:C# ASP.net Populate GridView with ImageButtonC# ASP.net 使用 ImageButton 填充 GridView
【发布时间】:2015-08-21 16:21:28
【问题描述】:

我对 c#、asp.net 和 Visual Studio 还是很陌生,我通常的阵容是 Java 和 Eclipse(以及 Casa 队长)。

所以我的实际问题如下。

           DataTable lowerTable = new DataTable();

        // create columns
        for (int i = 0; i < logic.gameSize; i++)
        {
            lowerTable.Columns.Add();
        }

        for (int j = 0; j < logic.gameSize; j++)
        {
            // create a DataRow using .NewRow()
            DataRow row = lowerTable.NewRow();


            // iterate over all columns to fill the row
            for (int i = 0; i < logic.gameSize; i++)
            {
                ImageButton button = new ImageButton();
                button.ImageUrl = "";
                button.AlternateText = logic.getValue(logic.bord.getLowerBord()[j, i].getFigur()).ToString();

                row[i] = button;
            }

            // add the current row to the DataTable
            lowerTable.Rows.Add(row);
            LowerField.Controls.Add(new ImageButton());
            LowerField.DataSource = lowerTable;
            try
            {
                LowerField.DataBind();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.ToString());
            }
        }
    }

我正在创建一个 DataTable 来填充我的 GridView ...但结果不是预期的充满按钮的网格,而是一个填充了文本的网格:System.Web.UI.WebControls.ImageButton。 我已经尝试过使用全球化的按钮,但这也没有帮助。 我是否忽略了一个简单的机械师?我实际上找不到任何适合 Google 的东西,或者至少找不到适合我实际需求的东西。

希望你能帮上忙 谢谢 比能狼

【问题讨论】:

  • 您需要使用 ASP.NET 控件,例如 GridViewListView(或许多其他控件中的任何一个)。如果你想动态地做,here's a link。否则,就像在控件的 ASPX 代码 like this 中设置某种 ItemTemplate 一样简单 - 只需更改模板字段以包含 ImageButton
  • 您的第一个链接非常有用,谢谢。我现在如何修复它:使用 OnDataBound 函数添加控件。

标签: c# asp.net gridview imagebutton


【解决方案1】:

您可以使用如下模板字段在网格视图中创建按钮:

//Put the a key value in DataKeyNames so you can get it in case of editing
<asp:GridView ID="gdvValores" runat="server" AutoGenerateColumns="False"  DataKeyNames="id">
 <asp:TemplateField HeaderText="Edit">
                        <ItemTemplate>
                            <asp:Button ID="btnEditar" CssClass="btnEditar" runat="server" OnClick="btnEditar_Click" />
                        </ItemTemplate>
                        <ItemStyle HorizontalAlign="Center" Width="35px" />
                    </asp:TemplateField>

在 .cs 中

protected void btnEditar_Click(object sender, EventArgs e)
{
//Get rowidex of gridview
    int linha = ((System.Web.UI.WebControls.GridViewRow)(((System.Web.UI.Control)(sender)).BindingContainer)).RowIndex;
//Get the ID in case of editing a item
    ViewState["codigo"] = gdvValores.DataKeys[linha]["id"].ToString();    

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多