Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if column exists in a DataGridView [duplicate]

I want to check if the column exist or not, I bind the data from a database to the DataGridView and I added link button as a column along with the DataGridView. I used the following code in the button click event.

con.Open();
SqlDataAdapter dadatagrid1 =
    new SqlDataAdapter("SELECT * FROM Stocktransferlocation", con);
DataSet dsdatagrid1 = new DataSet();
dadatagrid1.Fill(dsdatagrid1);
dataGridView_stocktransferlist.DataSource = dsdatagrid1.Tables[0];
con.Close();

DataGridViewLinkColumn btn = new DataGridViewLinkColumn();
dataGridView_stocktransferlist.Columns.Add(btn);
btn.HeaderText = "Click";
btn.Text = "Click Here";
btn.Name = "btn";
btn.UseColumnTextForLinkValue = true;

Here my problem: if I click add button the data is saved and click link is appearing. If I click next time click appears 2 times.

I just want to check if the column exists in the datagrid. I tried

if (dataGridView_stocktransferlist.Columns.Contains("Click") == true)

but it's not working.

like image 688
csura Avatar asked Sep 05 '25 03:09

csura


1 Answers

The Contains method fails because the column name is 'btn' and not 'Click'.

As you can see on the DataGridViewLinkColumn documentation, is the property Name that defines the column name the Contains method works on.

So your code should be

if (dataGridView_stocktransferlist.Columns.Contains("btn") == true
{
    .....
}

but I suggest to give a more meaningful name to your button like 'btnLinkForEdit' and change the if accordingly.

like image 190
Steve Avatar answered Sep 07 '25 21:09

Steve