Solved

CheckBox in datagrid in Windows Forms Application

Posted on 2004-10-26
495 Views
Last Modified: 2011-09-20
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
0
Question by:srao0
    11 Comments
     
    LVL 2

    Expert Comment

    by:dsabo
    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
     

    Author Comment

    by:srao0
    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
     
    LVL 2

    Expert Comment

    by:dsabo
    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
     

    Author Comment

    by:srao0
    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
     
    LVL 2

    Expert Comment

    by:dsabo
    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
     

    Author Comment

    by:srao0
    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
     
    LVL 2

    Expert Comment

    by:dsabo
    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
     

    Author Comment

    by:srao0
    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
     
    LVL 2

    Accepted Solution

    by:
    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
     

    Author Comment

    by:srao0
    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
     
    LVL 2

    Expert Comment

    by:dsabo
    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

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Article by: Ivo
    C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
    In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
    With the advent of Windows 10, Microsoft is pushing a Get Windows 10 icon into the notification area (system tray) of qualifying computers. There are many reasons for wanting to remove this icon. This two-part Experts Exchange video Micro Tutorial s…
    This video Micro Tutorial is the first in a two-part series that shows how to create and use custom scanning profiles in Nuance's PaperPort 14.5 (http://www.experts-exchange.com/articles/17490/). But the ability to create custom scanning profiles al…

    846 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    5 Experts available now in Live!

    Get 1:1 Help Now