CheckBox in datagrid in Windows Forms Application

Hi all,

I have a Windows Forms Application, in which there is a datagrid with a checkbox column,
now like in hotmail style but for my Windows Forms Application, i need to delete the records for which the checkbox column is checked
below is the code which is giving me an error

bool b =((CheckBox)((DataTable)dataGrid1.DataSource).Columns[0]).Checked ;

Cannot convert type 'System.Data.DataColumn' to 'System.Windows.Forms.CheckBox'

thanks in advance
srao0Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dsaboCommented:
Hello.

You cannot convert a DataColumn into a checkbox, there's a column style named DataGridBoolColumn, but you cannot make the convertion as you show above.

You could delete all the rows where the column is checked with this code.

DataTable t = (DataTable) dataGrid1.DataSource;
ArrayList toDelete = new ArrayList();

foreach(DataRow f in t.Rows)
{
    if(bool.Parse(f[0].ToString()))
    {
           toDetelte.Add(f);
    }
}

foreach(DataRow f in toDelete)
{
    t.Rows.Remove(f);
}

You cannot remove the row in the firs foreach because you will be modifying the collection and it will throw an exception.

I hope this helps,
0
srao0Author Commented:
hi dsabo,
 thanks for your response but the code u provided doesnt seem to distinguish between the checked and unchecked rows
it finds 'true' for all checked and unchecked....maybe its the way i have wired the checkbox column in the datagrid

                                string strConnection = @"Provider=Microsoft.Jet.OLEDB.4.0;Data
                                           Source=D:\\1_bak\\trial\\ProjectWorkSpace5\\AccessDB.mdb";
                        // Connection object
                         objSqlConnection  = new OleDbConnection(strConnection);
                  
                        //DataSet objDataSet = new  DataSet("trial");
                        DataSet objDataSet = new  DataSet();

                        // Retrive data from the table Order Detail
                        string strOrderDetails = "SELECT * FROM trial";
                        
                        OleDbDataAdapter objODAdapter = new OleDbDataAdapter(strOrderDetails,objSqlConnection);
                        //DataTable trialTable = objDataSet.Tables["trial"];
                        DataTable trialTable = new DataTable("trial");

                        //Add a Column with checkbox at last in the Grid  
                        DataColumn dtcCheck    = new DataColumn("delete");//create the data        
                        //column object with the name
                        dtcCheck.DataType      = System.Type.GetType("System.Boolean");
                        dtcCheck.DefaultValue  = false;
                        dtcCheck.ReadOnly = false;
                        //Add the above column to the Data Table
                        trialTable.Columns.Add(dtcCheck);
                        //Add DataTable to DataSet
                        objDataSet.Tables.Add(trialTable);
                        
                        objODAdapter.Fill(objDataSet,"trial");

                        //dataGrid1.DataSource = objDataSet.Tables["trial"];
                        dataGrid1.DataSource =trialTable;

and on button_click i have pasted your code

please let me know if you can find out where the problem could be
Thanks
0
dsaboCommented:
try this, maybe you are pointing to a wrong colmun. I change the way a refere to the column

DataTable t = (DataTable) dataGrid1.DataSource;
ArrayList toDelete = new ArrayList();

foreach(DataRow f in t.Rows)
{
    if(bool.Parse(f["delete"].ToString())) //index changed for column name
    {
           toDetelte.Add(f);
    }
}

foreach(DataRow f in toDelete)
{
    t.Rows.Remove(f);
}
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

srao0Author Commented:
this didnt make any difference either

bool.Parse(f["delete"].ToString())  returns true irrespective of whether i check the checkbox for marking the record for deletion or not
do u think i need to write some extra code in click event of the checkbox or something?...just guessing, because the checkbox value doesnt seem to be getting read

0
dsaboCommented:
You could try this:

DataTable t = (DataTable) dataGrid1.DataSource;
DataRow[] rs = t.Select("delete = true");

for(int x = 0; x < rs.Length; x++)
{
    t.Rows.Remove(rs[x]);
}

hope this solve your issue
0
srao0Author Commented:
hi dsabo....thanks for your responses, i got the checkbox working
but i have one more issure here...clicking the checkbox column seems to have 3 states

                          checkbox            bool.Parse(f["delete"].ToString())
clicking it once      check                    true
clicking it again      check(greyed)       (blank)
clicking it yet again   unchecked          false

why is there a third state for the checkbox in the middle? the code i am using to create the datagrid and checkbox is above

let me know of your suggestions...thanks
0
dsaboCommented:
Alright...

You need to create the tablestyle for that table, also you need to create the columnstyle for each column and add them to the collection tablastyle.ColumnStyle (I think, don´t have VS now).

You need to specify the columnstyle that you want, theres to options DataGridTextBoxColumn and DataGridBoolColumn, you must chose the one that match the type of the column.

For the DataGridBoolColumn, there's a property AllowNull, that you must set false in order to disable the three state.

Hope this helps..
0
srao0Author Commented:
i am not getting how i could tablestyle and columnstyle for just one column in my datagrid (the delete checkbox column) and get the rest of the columns plainly from the "select * from trial" query

any code snippets would be of great help...thanks
0
dsaboCommented:
Here's a guide:

DataTable tabla = new DataTable("Test");
SqlAdapter1.Fill(tabla);

DataGridTableStyle style = new DataGridTableStyle();
style.MappingName = tabla.TableName;

DataGridColumnStyle colstyle;

foreach(DataColumn col in tabla.Columns)
{
    if (!col.DataType.Equals(typeof(System.Boolean))
    {
      colstyle= new DataGridTextBoxColumn();
    }
    else
    {
      colstyle = new DataGridBoolColumn();
      DataGridBoolColumn tmp = (DataGridBoolColumn)estilocol;
      tmp.AllowNull = false;
    }
    colstyle.MappingName = col.ColumnName;
    style.GridColumnStyles.Add(colstyle);
}

table.TableStyle.Add(style);

hope, this helps you...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
srao0Author Commented:
thanks dsabo! i have got that working

i have just one more thing here.....how do i make a datagrid to be in non-append mode i.e im able to modify only the "delete" column checkbox to choose whether to delete the record or not but i dont wanna be able to add new rows/records to the DataGrid.
if i make the datagrid readonly, it becomes non-appendable but then im not able to access the "delete" checkbox column

any suggestions...thanks
0
dsaboCommented:
Hi, I'm glad that you solve the issue.

That last petition is very simple, there's a property for the DataGridBoolColumn and for DataGridTextColumn that allows to set the column as readonly.

foreach(DataColumn col in tabla.Columns)
{
    if (!col.DataType.Equals(typeof(System.Boolean))
    {
     colstyle= new DataGridTextBoxColumn();
    }
    else
    {
     colstyle = new DataGridBoolColumn();
     DataGridBoolColumn tmp = (DataGridBoolColumn)estilocol;
     tmp.AllowNull = false;
    }
    colstyle.MappingName = col.ColumnName;
    if(colstyle.MappingName != "delete")           //new line
        colstyle.ReadOnly = true;                       //new line
    style.GridColumnStyles.Add(colstyle);
}
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.