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

落爺英雄遲暮 提交于 2020-01-06 06:09:38

问题


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:


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



来源:https://stackoverflow.com/questions/46063385/getting-and-error-i-cannot-fix-when-trying-to-add-a-button-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!