Димитър Грудев Димитър Грудев - 2 months ago 14
C# Question

Adding bool column in DataTable with value

i try to add column in datatable :

dt.Columns.Add(new DataColumn("BoolProperty", typeof(bool)));


and try to set value - false:

DataRow dr = dt.NewRow();
dr["BoolProperty"] = false;


But it does not work! Here is code:

try
{
con.server = this.server;
con.user = this.user;
con.password = this.password;
con.OpenConnection();
con.SqlQuery(Properties.Resources.databaseCatalogResource);
DataTable dt = con.QueryEx();
con.da.Fill(dt);
dt.Columns.Add(new DataColumn("BoolProperty", typeof(bool)));
DataRow dr = dt.NewRow();
dr["BoolProperty"] = false;
dataGrid.ItemsSource = dt.DefaultView;

}
catch (Exception ex)
{
MessageBox.Show("Грешка във връзката.", "Грешка");
}


This is what happens :
:)

but i need this column to be unchecked.

ASh ASh
Answer Source

create a boolean dataColumn with a default value false before filling data. (A default value is the value that is automatically assigned to the column when a DataRow is created)

DataTable dt = con.QueryEx();
var column = new DataColumn("BoolProperty", typeof(bool));
column.DefaultValue = false;
dt.Columns.Add(column);
con.da.Fill(dt);


lines

DataRow dr = dt.NewRow();
dr["BoolProperty"] = false;

are basically useless. dr is a new empty row, isn't added to a table and doesn't change flags in other rows