Datagrid View Button repeat

痞子三分冷 提交于 2019-12-25 04:35:21

问题


I have added button to datagrid view but when ever the function is called more than once then new button adds I need to stop this addition

  void AddtoGrid()
    {
        try
        {                
            table = new DataTable();
            bcol = new DataGridViewButtonColumn();
            bcol.HeaderText = "Action ";
            bcol.Text = "Delete";
            bcol.Name = "deleteUserButton";
            bcol.UseColumnTextForButtonValue = true;                

            table.Columns.Add("Name");
            table.Columns.Add("Type");
            table.Columns.Add("Status");
            table.Columns.Add("Date Created");
            table.Columns.Add("Action");
            for (int i = 0; i < userAction.UserName.ToArray().Length; i++)
            {
                row = table.NewRow();
                asc.Add(userAction.UserName[i]);
                row["Name"] = userAction.UserName[i];
                row["Type"] = userAction.UserType[i];
                row["Status"] = userAction.UserStatus[i];
                row["Date Created"] = userAction.DateCrea[i];
                row["Action"] = bcol.Text;
                table.Rows.Add(row);
            }

            UsersView.DataSource = table;
            UsersView.AllowUserToAddRows = false;//To remove extra row at the end
            UsersView.Columns.Add(bcol);
        }
        catch (Exception ca)
        {
            MessageBox.Show(ca.ToString());
        }
    }//End Function for Getting Present Users

回答1:


I'm not quite sure I understand your question, though I believe that you need to encapsulate creation of the new column into it's own method and only call it once - in the constructor for instance.

For example:

void CreateDeleteColumn()
{            
    bcol = new DataGridViewButtonColumn();
    bcol.HeaderText = "Action ";
    bcol.Text = "Delete";
    bcol.Name = "deleteUserButton";
    bcol.UseColumnTextForButtonValue = true;

    UsersView.Columns.Add(bcol);
}

That should stop it adding a column every time you populate the list view.

Hope this helps and sorry if I misunderstood.

Tony



来源:https://stackoverflow.com/questions/4167136/datagrid-view-button-repeat

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