Link to home
Start Free TrialLog in
Avatar of srao0
srao0

asked on

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
Avatar of dsabo
dsabo
Flag of Venezuela, Bolivarian Republic of image

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,
Avatar of srao0
srao0

ASKER

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
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);
}
Avatar of srao0

ASKER

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

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
Avatar of srao0

ASKER

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
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..
Avatar of srao0

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of dsabo
dsabo
Flag of Venezuela, Bolivarian Republic of image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of srao0

ASKER

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
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);
}