Question

In my windows application, I want to add linklabel i.e Delete against each record in the datagridview and I am populating datagridview from the database like below:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace search
{
    public partial class Form1 : Form
    {
        SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\Administrator\\Documents\\Contact.mdf;Integrated Security=True;");
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        public Form1()
        {
            InitializeComponent();

        }
        public void bindDatagridview()
        {
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
            da.SelectCommand = new SqlCommand("Select * from contactsinfo", connection);
            da.Fill(ds);

            dataGridView1.DataSource = ds.Tables[0];
            ds.Tables[0].Columns.Add("Delete", typeof(String));
            foreach (DataGridViewRow r in dataGridView1.Rows)
            {
                DataGridViewLinkCell lc = new DataGridViewLinkCell();
                lc.Value = r.Cells[2].Value = "Delete";
                dataGridView1[2, r.Index] = lc;
            }
            clear();
        }
        public void clear()
        {
            textBox1.Text = string.Empty;
            textBox2.Text = string.Empty;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            bindDatagridview();
        }
    }
}

The above code add Delete linkLabel against each data in the row, but when I i click on the headertext of the datagridview, linklabel convert into the simple text, how it is, and is there any way to add Delete linklabel against each data in the row. kindly suggest me, waiting for your reply. Thanks.

Était-ce utile?

La solution

I think your problem is the type of the Column!

var col = new DataGridViewLinkColumn();
col.DataPropertyName = "Delete";
col.Name = "Delete";

ds.Tables[0].Columns.Add(col);

should do it.

Autres conseils

Click on the column header to sort the column, and see if the underline stays in the column (dgvLink).

This underline disappears when you try to sort the column.

I am using this and its working fine.

DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn();
dgvLink.UseColumnTextForLinkValue = true;
dgvLink.LinkBehavior = LinkBehavior.SystemDefault;
dgvLink.HeaderText = "";
dgvLink.Name = "lnk_delete";
dgvLink.LinkColor = Color.Blue;
dgvLink.TrackVisitedState = true;
dgvLink.Text = "Delete";
dgvLink.UseColumnTextForLinkValue = true;
dataGridView1.Columns.Add(dgvLink);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top