Getting and error I cannot fix when trying to add a button column

805 views Asked by At

I am having trouble fixing an error that I keep getting when I try to add a button column to my table. The error is: Argument 1: cannot convert from 'System.Windows.Forms.DataGridViewButtonColumn' to 'System.Web.UI.WebControls.DataControlField'

It is basically saying that I cannot use the local variable 'btn' in the line

        gridViewStudent.Columns.Add(btn);

in the following code:

        gridViewStudent.DataSource = table;
        gridViewStudent.DataBind();

        DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
        gridViewStudent.Columns.Add(btn);
        btn.HeaderText = "Click Data";
        btn.Text = "Click Here";
        btn.Name = "btn";
        btn.UseColumnTextForButtonValue = true;
1

There are 1 answers

2
Tetsuya Yamamoto On BEST ANSWER

DataGridViewButtonColumn intended to use with WinForms' DataGridView control. In Web Forms context you may use ButtonField instead:

var btn = new ButtonField();
btn.HeaderText = "Click Data";
btn.Text = "Click Here";

gridViewStudent.Columns.Add(btn);

Since there is no Name and UseColumnTextForButtonValue properties present for ButtonField control, their assignments are just omitted.

Alternatively you can use prepared asp:ButtonField inside Columns section in ASPX page:

<asp:GridView runat="server" ID="gridViewStudent" ... />
    <Columns>
        <%-- other fields --%>
        <asp:ButtonField HeaderText="Click Data" Text="Click Here" />
    </Columns>
</asp:GridView>

Similar issue:

Programmatically Add ButtonColumn to GridView From DataTable