简体   繁体   中英

System.InvalidCastException when work with datagridview

    private void VPfn_GenInvoice()
    {
        int iid = Convert.ToInt16(tid.Text);
        int cid = Convert.ToInt16(tcid.Text);
        double subtotal = Convert.ToDouble(tst.Text);
        double atax = Convert.ToDouble(tat.Text);
        double discount = Convert.ToDouble(tdis.Text);
        double total = Convert.ToDouble(ttotal.Text);

        StringBuilder iQ = new StringBuilder();

        foreach(DataRow x in invoice_data.Rows)
        {
            int iiid = VPfunctions.VPfn_N2ID_itm(x["item_name"].ToString());
            string dQuery = "INSERT INTO `invoice_data` (id, sr, item_id, item_qty, item_unit, item_vat, amount) " +
                "VALUES(" + iid + ", " + x["serial_number"].ToString() + ", " + iiid + ", " + x["item_qty"].ToString()
                + ", " + x["item_unit"].ToString() + ", " + x["item_vat"].ToString() + ", " + x["amount"].ToString() + ")";
            iQ.Append(dQuery);
            iQ.AppendLine();
        }

        //Updating main Invoice DB
        string query = "INSERT INTO `invoice` ( id, cusid, cdate, mdate, subtotal, atax, discount, total) VALUES (?A,?B,?C,?D,?E,?F,?G,?H)";
        xxtb.Text = iQ.ToString();
        /**
        try
        {
            //inserting into invoice
            con.Open();
            MySqlCommand xv = new MySqlCommand(query, con);
            xv.Parameters.AddWithValue("?A", iid.ToString());
            xv.Parameters.AddWithValue("?B", cid.ToString());
            xv.Parameters.AddWithValue("?C", DateTime.Now.ToString());
            xv.Parameters.AddWithValue("?D", "-");
            xv.Parameters.AddWithValue("?E", subtotal.ToString());
            xv.Parameters.AddWithValue("?F", atax.ToString());
            xv.Parameters.AddWithValue("?G", discount.ToString());
            xv.Parameters.AddWithValue("?H", total.ToString());
            xv.ExecuteNonQuery();

            //Inserting into invoice_data
            MySqlCommand ixv = new MySqlCommand(iQ.ToString(), con);
            ixv.ExecuteNonQuery();
        }
        catch
        {

        }
        finally
        {
            con.Close();
        } **/
    }

and I am getting error as follows: System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Data.DataRow'.'

Now ,I am trying to make invoicing software for my own but I am getting this error and yes, I am using Visual studio 2017RC and windows 10 64bit.

foreach中的x变量必须为DataGridViewRow类型,如下修改代码:

foreach(DataGridViewRow x in invoice_data.Rows)

My guess is that invoice_data.Rows is a collection of DataGridViewRow and your foreach is trying to cast it to DataRow. Does it work if you change your foreach to this:

foreach(DataGridViewRow x in invoice_data.Rows)
...
foreach(DataRow x in invoice_data.Rows)

This line has the wrong type for x . DataRow is a row in an abstract DataTable , not the GUI element DataGridView . foreach does the silent casting, as the Rows property returns an object of type DataGridViewRowCollection , and for backwards compatibility, this type only implements IEnumerable and not IEnumerable<DataGridViewRow> . That's the reason the compiler didn't warn you about an invalid cast.

The fix is therefore easy:

foreach(DataGridViewRow x in invoice_data.Rows)

The properties on x are a bit different, though. You have to use the Cells property to obtain the data. You can use either the column name, or the column index. One of these should work:

x.Cells["item_name"].ToString()

x.Cells[0].ToString()

Provided the name is the first column.

People already give the right answer

foreach(DataGridViewRow x in invoice_data.Rows)

but if someone wants to know how to read data from the datagridview then you have to write these lines

foreach(DataGridViewRow x in invoice_data.Rows){
Console.WriteLine(x.Cells["ColumnName"].Value.ToString());}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM