我在c#中有一个datagridview。数据源是List。所有的文件都被添加为列,最后我添加了另一列:DataGridViewLinkColumn, 如果我进行刷新/重新加载,DataGridViewLinkColumn将被添加多次。 任何帮助都会非常有用。
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();
}
答案 0 :(得分:1)
要避免多次添加同一列,请在添加之前检查gridview中是否存在此列。要进行检查,您可以使用以下代码。
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();
}