Click here to Skip to main content
16,005,038 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi im using the following code to copy a gridview dataschema and checked rows to a separate table.
It works very fine when all the rows are checked. but giving an error
object cannot be cast from dbnull to other types
when i left few rows unchecked in the beginning.

Please help to solve this issue. i need to get the only checked row data into that variable.

Thanks in advanced...

What I have tried:

var bindingsource = (BindingSource)dgv_summary.DataSource;
                DataTable tbl = ((DataTable)bindingsource.DataSource).Clone();
                var rows = dgv_summary.Rows.OfType<DataGridViewRow>()
                                        .Where(r => Convert.ToBoolean(r.Cells[" "].Value))
                                        .Select(r => ((DataRowView)r.DataBoundItem).Row);
                foreach (var row in rows)
                {
                    tbl.ImportRow(row);
                }
                DataTable dt_Cust = tbl.DefaultView.ToTable(true, "GL_ACNO");
Posted
Updated 17-Jan-18 17:57pm

try casting in a method

var rows = dgv_summary.Rows.OfType<DataGridViewRow>()
                                   .Where(r =>  GetBoolValue( r.Cells[" "].Value))
                                   .Select(r => ((DataRowView)r.DataBoundItem).Row);


private bool GetBoolValue(object value) {
        string val = Convert.ToString(value);
        bool returnValue ;
        Boolean.TryParse(val, out returnValue);
        return returnValue;
    }
 
Share this answer
 
Comments
chaitanya556 18-Jan-18 0:17am    
Thank you so much... It Worked :-)
Karthik_Mahalingam 18-Jan-18 1:04am    
welcome
Most likely it is the statement:
C#
r => Convert.ToBoolean(r.Cells[" "].Value)

If it is dbnull then it cannot be converted to boolean as it has no implicit value. You need to add some code to ignore rows with dbnull entries.
 
Share this answer
 
Comments
chaitanya556 17-Jan-18 22:36pm    
ya i know that.. im looking for some code suggestions. if you can suggest me some code to ignore the rows with null values in the above code.

Thank you
Richard MacCutchan 18-Jan-18 5:17am    
Just check the value to see if it is dbnull.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900