0

I use the following code to bind DataTable with DataGridView:

DataTable dt = new DataTable();   
dt = serviceSqlite.select(new Pacients());    
dataGridView1.DataSource = dt;

I want to add custom columns in dt it should be one CheckBox and Image.

How to do that?

4
  • You can add them to your DataGridView like this dataGridView1.Columns.Add(new DataGridViewCheckBoxColumn()); Commented Aug 30, 2017 at 19:31
  • Can you share full example? With setting name of columns? Commented Aug 30, 2017 at 19:34
  • You can add columns to the table; add the 1st one a bool and the 2nd one as byte[] . Much more flexible when it comes to sorting or filtering.. Commented Aug 30, 2017 at 19:35
  • 1
    @OPV OK. Check my answer. Commented Aug 30, 2017 at 19:37

1 Answer 1

1

You can add them to your DataGridView. Like this:

var checkBox = new DataGridViewCheckBoxColumn
{
    Name = "checkBox",
    HeaderText = @"checkBox",
    Width = 70
};
//Set other properties...
dataGridView1.Columns.Add(checkBox);

And same for Image:

DataGridViewImageColumn image = new DataGridViewImageColumn();
//....

Also if you want the new column to be appear in another column you can replace dataGridView1.Columns.Add(checkBox); with following:

dataGridView1.DataSource = dt;
var checkBox = new DataGridViewCheckBoxColumn
{
    Name = "checkBox",
    HeaderText = @"checkBox",
    Width = 70
};
//Set other properties...
dataGridView1.Columns.Insert(1, checkBox);

And if you want to add it to your DataTable you can add it as boolean field in the DataTable:

dt.Columns.Add(new DataColumn("checkBox", typeof(bool)));
dataGridView1.DataSource = dt; 

So when you bind the DataTable to your DataGridView, a CheckBoxColumn is created for this boolean field.

Sign up to request clarification or add additional context in comments.

11 Comments

After how to bind with DataTable?
I dont understand, I need to add new column to DataTable or to dataGridView1? Will it work correct? When one part of data from DataTable one added manually?
@OPV You need to add column to your DataGridView to show on your form. Just add my answer to your code and you will see the result.
@OPV, Pick your poison... Bind to your DataTable then, add a column to the DataGridView... Or... Add the column to your DataTable, then bind the DataGridView to your DataTable. The Global scope of your requirements should tell you which way to swing. Personally, I'd alter my DataTable, and then bind it to the DataGridView.
How can I change DataTable for new column CheckBox, I need to add empty column to DataTable? Can you edit your answer please
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.