0

I want to insert data from empty DataGridView to database (the DataGridView doesn't load from the database, but I just take the value in DataGridView).

I tried this code:

private void vButton12_Click(object sender, EventArgs e)
    {
        MySqlConnection conn = new MySqlConnection("server=localhost;User Id=root;database=sma9");
        DataTable dtable = new DataTable();
        MySqlDataAdapter adp = new MySqlDataAdapter("select * from tdetpinjam", conn);
        adp.Fill(dtable);            
        for (int i = 0; i < dtable.Rows.Count; i++)
        {
            MySqlDataAdapter adp1 = new MySqlDataAdapter("INSERT INTO tdetpinjam (nopinjam,kodebuku,jumlah,tglkembali,status) VALUES ('" + dtable.Rows[i][dtable.Columns.IndexOf("Column1")] + "','" + dtable.Rows[i][dtable.Columns.IndexOf("Column2")] + "','" + dtable.Rows[i][dtable.Columns.IndexOf("Column3")] + "','" + dtable.Rows[i][dtable.Columns.IndexOf("Column4")] + "','" + dtable.Rows[i][dtable.Columns.IndexOf("Column5")] + "')", conn);
            conn.Open();
            adp1.Fill(dtable);
            conn.Close();
        }
    }

But I get the error "cannot find column -1".

What is wrong in my code? What is the best solution to do this?

0

2 Answers 2

1

I guess one of these return -1:

dtable.Columns.IndexOf("ColumnX")
Sign up to request clarification or add additional context in comments.

Comments

0

what you are doing is completely wrong, there is no datagrid related code in your code, you just get data from database table and loop though each row returned and try to insert same data again to same table in the database. in each item you try to fill same table from database.

actual error occur when you get index of given column, you need to validate it before insert

    if(dtable.Columns.IndexOf("Column1") != -1 && 
    dtable.Columns.IndexOf("Column2") != -1 && 
    dtable.Columns.IndexOf("Column3") != -1 && 
    dtable.Columns.IndexOf("Column4") != -1 && 
    dtable.Columns.IndexOf("Column5") != -1)
    {
       // insert related code 
    }

if you need to insert records using MySqlDataAdapter, fist set select, update and insert commands of MySqlDataAdapter, then you can call MySqlDataAdapter.Update method.

check this for more info.

EDIT

foreach (DataGridViewRow row in dataGrid.Rows)
{
         foreach (DataGridViewCell cell in row.Cells)
        {
            string value = cell.Value.ToString();

        }
 }

1 Comment

so how to read the data from datagridview ? so i can insert it to database ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.