简体   繁体   中英

Insert from datagridview to database

Hi i would like to ask is there any way to insert the column names automatically?

for (int i = 0; i < ADODB.Rows.Count; i++) 
 {
  StrQuery = @ "INSERT INTO tableName VALUES (" + ADODB.Rows[i].Cells["ColumnName"] + ", " + ADODB.Rows[i].Cells["ColumnName"] + ");";
  comm.CommandText = StrQuery;
  comm.ExecuteNonQuery();
 }

Try this

dataGridView1.Rows[0].Cells[i].Text // i is column number

or

dataGridView1.Rows.HeaderRow.Cells[i].Text  // i is column number

If I didn't understand wrong, what about this?

string[] columnNames = dataGridView1.Columns.Cast<DataGridViewColumn>()
                                            .Select(x => x.HeaderText).ToArray();
// get column names to string array
string joinedArray = string.Join(",", columnNames);
// set them into string seperating with ,
string sql = "INSERT INTO tableName VALUES (" + joinedArray + ")";

Hope helps,

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