开发者

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 = sq开发者_C百科lSelect;
    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 +=.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜