简体   繁体   中英

Change a Cell into a Button in DataGridView

I have a databound DataGridView. I want the cells of the two columns to contain a button instead of a regular cell.
Edit: Solved, now I need to figure out how to disable the button when a Cell contains NULL.

To enable adding of Columns to a specified position to a DataBound Datagridview, we have to set the Datagridviews AutoGenerateColumns Property to False before adding the Column.
Without doing so, all Columns that will be added will be placed on the right most end of the Datagridview and it will affect the first Column too.

But remember that the Colummn.Index Property will be affected.

dgv_dt is a DataTable  
dgv is the DataGridView  

dgv.AutoGenerateColumns=True

dgv.DataSource=dgv_dt
dgv.ClearSelection
dgv.Columns(0).HeaderText="FirstName"
dgv.Columns(1).HeaderText="Company ID"
dgv.Columns(2).HeaderText="Recent Picture"
dgv.Columns(2).Visible=False
dgv.Columns(3).HeaderText="Address"
dgv.Columns(4).HeaderText="Alive"

dgv.AutoGenerateColumns=False

Dim btn As New DataGridViewButtonColumn()
btn.HeaderText = "Click Data"
btn.Text = "Click Here"
btn.Name = "btn"
dgv.Columns.Insert(2,btn)

The code above will display the Datagridview and its Column.Index like this:

dgv.Columns(1) First Name
dgv.Columns(2) Company ID
dgv.Columns(3) Recent Picture 'This column is hidden, if this Contains NULL, ButtonCell is enabled/clickable
dgv.Columns(0) ButtonCell
dgv.Columns(4) Address
dgv.Columns(5) Alive

The Columns Company ID and Recent Picture contains a BLOB or NULL, if its a BLOB, the cell will be an Enabled Button and a Disabled Button if its NULL.

Set existing column to hidden .Visible = false .
Then add DataGridViewButtonColumn and check value of CompanyID column

if BLOB then button column enabled
if NULL then button column disabled

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM