Joe Baker
Joe Baker

Reputation: 196

How can I put a column of Button in an ASP GridView?

I'm pretty new to ASP.Net, and I've hit a bit of a wall. I'm binding my GridView to a TableAdapter -- that part is working fine -- and I want to add a column that contains buttons, all of them with the same text.

Here's a fragment of my aspx that creates the GridView:

   <asp:GridView ID="LSResultsGrid" runat="server" CellPadding="3" CellSpacing="5">
   </asp:GridView>

And here's what I'm trying to do in my C# code:

    LSResultsAdapter = new LSResultsTableAdapter();
    LSResultsAdapter.CreateQualificationSamples(QualID, 0);

    LSResultsGrid.DataSource = LSResultsAdapter.GetLSSampleData(1);

    Button b = new Button();
    b.Text = "Show";

    DataColumn col = new DataColumn("Reps", typeof(Button));
    col.DefaultValue = b;

    var lsResultsTable = ((QCServer.HVIMillData.LSResultsDataTable)LSResultsGrid.DataSource);
    lsResultsTable.Columns.Add(col);

    LSResultsGrid.DataBind();

If I remove the "typeof(Button)" parameter from the DataColumn constructor, then my table shows with the new column -- but the text on the buttons is "System.Web.UI.WebControls.Button"; if I leave the parameter as shown here, the column just doesn't appear at all (there is no exception thrown).

Thanks, anyone who can lend a hand.

Upvotes: 0

Views: 2815

Answers (1)

BasicIsaac
BasicIsaac

Reputation: 187

There are a couple of ways to add a button in gridview. Your method will work, just change col.DefaultValue = b; to col.DefaultValue = b.Text; but this is a difficult method for a beginner.

A couple of easier methods can be accomplished in the markup itself: inside gridview you can add: type 1:

<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Show" />
</Columns>

type 2:

<Columns>
<asp:TemplateField>
<HeaderTemplate> My Action
</HeaderTemplate>
<ItemTemplate>
<asp:Button ID="showbtn" runat="server" text="Show"  CommandArgument='<%#Eval("Reps")%>' OnClick="showbtn_Click" />
</ItemTemplate>
</asp:TemplateField>

with the second type of button, build a method to match OnClick="showbtn_Click" that will perform your desired action when the button is clicked. Same with the first method.

Here is a third type, if you really must do it from the codebehind, add the button field to your grid, not the datatable:

    ButtonField col = new ButtonField();
    col.ButtonType = ButtonType.Button;
    col.DataTextField = ("Reps"); //or whatever bound column you want to show.
    LSResultsGrid.Columns.Add(col);

Hope this helps!

Upvotes: 1

Related Questions