简体   繁体   中英

Writing to more than one Column in Access from more than one Column in Datagrid

I'm stuck with a bit of a problem here. I'm importing data from a datagridview to an Access database with OLEDB and an INSERT Statement but now I'm stuck because the Access table has multiple columns that has the is required option turned on so I'm wondering how can I use the INSERT Statement to get the values from more than one column in datagrid to more than one column in Access. My code works this way you click on any cell in the datagrid and than on the column name in the listview. Here is my code and sorry if it's a little(OK a lot messy) but I'm new to coding.

private void datExcel_CellClick(object sender, DataGridViewCellEventArgs e)
{
    string sqlSelect = "SELECT [" + datExcel.Columns[e.ColumnIndex].Name + "] FROM [" + cboSource.Text + "]  ";
    _ColumnValues = new List<string>();
    OleDbCommand cmd = _SourceConn.CreateCommand();
    cmd.CommandText = sqlSelect;
    OleDbDataReader reader = cmd.ExecuteReader();

    while (reader.Read())
    {
        if (!string.IsNullOrWhiteSpace(reader.GetValue(0).ToString()))
        {
            _ColumnValues.Add(reader.GetValue(0).ToString());
        }
    }
    reader.Close();
}

and another part if you need it

private void lvwDestination_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        _tablesname = lvwDestination.SelectedItems[0].Text;

        for (int i = 1; i < _ColumnValues.Count; i++)
        {
           string Colname = _ColumnValues[i];
           string sqlIns = "INSERT INTO " + cboTableName.Text + " ([" + _tablesname + "]) VALUES ('" + Colname + "')";
           OleDbCommand cmd = _DestConn.CreateCommand();
           cmd.CommandText = sqlIns;
           cmd.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

The best way to do this is by building your INSERT INTO Statement Dynamically using the += operator BUT you can also use StringBuilder. In my case I used +=.

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