0

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;
Sohee
  • 23
  • 5
  • 1
    As the error is trying to tell you, you're trying to mix two different namespaces. Don't do that. – SLaks Sep 05 '17 at 21:12
  • What makes you think you can add a `Windows.Forms` control to a ASP.NET form? – mjwills Sep 05 '17 at 21:32
  • I'm trying to follow some other code that I found online here when trying to add a button column, and they all seem to follow the same structure, so I am not exactly sure what is different. Do i need to post more of my code? – Sohee Sep 06 '17 at 00:25

1 Answers1

1

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

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • I have made this change and the build is now successful, but the buttons and column header still do not show up. Is there perhaps a specific place where this code should be? I currently have it after I data bind the data table. – Sohee Sep 06 '17 at 01:58
  • 1
    That's probably more suitable to create a follow-up question. Post your fixed gridview markup & code behind on that new question and put a link to this question to see your effort. – Tetsuya Yamamoto Sep 06 '17 at 02:04