Alfred Waligo
Alfred Waligo

Reputation: 2919

how to add a checkbox to a datagridview that is bound to a datasource?

I am new to c#. I need to have a checkbox field in the "selected" column of my datagridview instead of the "False"(or "True") text that is showing currently. This datagridview is databound and the data is obtained by reading an xml file. How can I achieve this?

before writing to the xml file, this is what i did.

DataTable dtGens = new DataTable(); //creates a new Datatable object for the Gens

dtGens.TableName = "Gen Types";

DataColumn dc1 = new DataColumn("Generator");  
DataColumn dc2 = new DataColumn("alpha");
DataColumn dc3 = new DataColumn("beta");
DataColumn dc4 = new DataColumn("circuit breaker");
DataColumn dc5 = new DataColumn("description");
DataColumn dc6 = new DataColumn("Selected",System.Type.GetType("System.Boolean"));

dtGens.Columns.Add(dc1); //associates the columns to the dtGens datatable
dtGens.Columns.Add(dc2);
dtGens.Columns.Add(dc3);
dtGens.Columns.Add(dc4);
dtGens.Columns.Add(dc5);
dtGens.Columns.Add(dc6);

DataRow drow;
for (int i = 0; i < 50; i++)
{
    drow = dtGens.NewRow();
    drow["Generator"] = "Gen " + (i + 1).ToString();
    drow["alpha"] = 0.0;
    drow["beta"] = 0.0;
    drow["circuit breaker"] = 0.0;
    drow["description"] = "myGen";
    drow["Selected"] = false;
    dtGens.Rows.Add(drow);

}

//creates a new DataSet Object that will help write generator data to XML
DataSet feederProject = new DataSet();
feederProject.Tables.Add(dtGens);
feederProject.WriteXml("Generators.xml");
//preview  
DataSet feederProject = new DataSet();
feederProject.ReadXml("Generators.xml");
dataGridViewLoadsDGs.DataSource = feederProject.Tables[0];

Upvotes: 1

Views: 7379

Answers (2)

Ripple
Ripple

Reputation: 1265

A column bound to boolean type automatically shows checkboxes. The problem is that the schema information of your DataTable is lost when it's written into the XML. To prevent that, you can use an overload of DataSet.WriteXml that takes XmlWriteMode as a parameter, which allows you an option to write the schema information.

feederProject.WriteXml("Generators.xml", XmlWriteMode.WriteSchema);

Upvotes: 4

Angel.Chorbadzhiev
Angel.Chorbadzhiev

Reputation: 490

To be able to represent a bound boolean data as a check box column you need to set AutoGenerateColumns property of the DataGridView to false. Then add columns manually and for the column that must be checkbox column set a instance of DataGridViewCheckBoxColumn:

dataGridViewLoadsDGs.AutoGenerateColumns = false;
...
dataGridViewLoadsDGs.Columns.Add(new DataGridViewCheckBoxColumn());

Upvotes: 2

Related Questions