Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

CheckBox in datagrid in Windows Forms Application

Posted on 2004-10-26
11
Medium Priority
?
514 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
Comment
Question by:srao0
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
11 Comments
 
LVL 2

Expert Comment

by:dsabo
ID: 12418290
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
ID: 12418389
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
ID: 12418525
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:srao0
ID: 12434843
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
ID: 12435545
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
ID: 12437042
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
ID: 12437356
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
ID: 12438020
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:
dsabo earned 1200 total points
ID: 12438135
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
ID: 12440302
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
ID: 12441281
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

Featured Post

Enroll in October's Free Course of the Month

Do you work with and analyze data? Enroll in October's Course of the Month for 7+ hours of SQL training, allowing you to quickly and efficiently store or retrieve data. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

610 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