I have a datagridview in c#. The datasource is a List. all the fileds are being added as columns, at the end I add another column: DataGridViewLinkColumn, If i do a refresh/reload the DataGridViewLinkColumn is being added more then once. Any help would be much appriciated.
private void bidListToGridT(List<Item> list)
{
dataGridView1.DataSource = null;
dataGridView1.DataSource = list;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.AllowUserToAddRows = false;
int i = 1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells["NO"].Value = i;
i++;
}
dataGridView1.Columns[1].HeaderText = "Id";
dataGridView1.Columns[2].HeaderText = "Name";
DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
Deletelink.UseColumnTextForLinkValue = true;
Deletelink.HeaderText = "Delet";
Deletelink.DataPropertyName = "lnkColumn";
Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
Deletelink.Text = "Delete";
dataGridView1.Columns.Add(Deletelink);
dataGridView1.Refresh();
}
To Avoid adding same column many times, Check whether such column existing in the gridview or not, Before adding them. For checking this you can use the following code.
bool hasDeleteColumn=false;
foreach (DataGridViewColumn item in dataGridView1.Columns)
{
if (item.GetType() == typeof(DataGridViewLinkColumn) && item.HeaderText=="Delete")
{
hasDeleteColumn = true;
break;
}
}
if(!hasDeleteColumn)
{
// Adding columns if not existing
DataGridViewLinkColumn Deletelink = new DataGridViewLinkColumn();
Deletelink.UseColumnTextForLinkValue = true;
Deletelink.HeaderText = "Delete";
Deletelink.DataPropertyName = "lnkColumn";
Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
Deletelink.Text = "Delete";
dataGridView1.Columns.Add(Deletelink);
dataGridView1.Refresh();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.