简体   繁体   中英

Insert to Database from DataGridView

I have a class Connect to connect to the Database. Here is the code:

    class Connect
{
    SqlConnection con;
    public Connect()
    {
        String connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Application.StartupPath + @"\Database1.mdf;Integrated Security=True;User Instance=True";
        con = new SqlConnection(connectionString);
    }

    public DataTable executeSelect(String query)
    {
        con.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(query, con);
        DataTable dt = new DataTable();
        adapter.Fill(dt);
        con.Close();

        return dt;
    }

    public void execute(String query)
    {

        con.Open();
        SqlCommand cmd = new SqlCommand(query, con);
        cmd.ExecuteNonQuery();

        con.Close();
    }
}

And i have DataGridView like this:

我的资料

How is the code to insert all data from that DataGridView to the Database ?

If you write your last sentence to Google you will get this link at first. And your answer is there.

I think you need to use loop insertion.You have to put all data in a list. Or try this

because you have a DataTable in your post codes.

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