简体   繁体   中英

How to Update data in the dataGridview ONLY

My application imports a sheet from an excel file with only the header column names into a new dataGridView Table. To keep it easy lets say the Column names are; Name, City, State, Status. I "hard code" the first 2 entries as Jack, Detroit, MI, Missing; and Mike, Chicago, IL, Missing. Next I import an XML file that adds more entries. I have the code looking for the original 2 entries, if found, I want it to "update" or "re-edit" the Missing to Found. (I want this to happen ONLY in the dataGridView Table. The sql examples I'm finding are all aimed at updating the original database. I want it to only update the dataGridView table.

This code is designed to update the excel file.

sql = "UPDATE " + myNameRange + " SET " + mySET + "' WHERE " + myWHERE + "'";

Is there a way I can do something like this only to change the data in the dataGridView?

Method to bring in sheets from excel

public static void loadData(string SheetName, DataGridView MyDataGrid, string filePathMain)
{
    string pathCon = "Provider=Microsoft.Ace.OLEDB.12.0; Data Source=" + filePathMain + ";Extended Properties=\"Excel 8.0; HDR=YES;IMEX=3;READONLY=FALSE\";";
    OleDbConnection conn = new OleDbConnection(pathCon);
    OleDbCommand cmd = new OleDbCommand("select * from [" + SheetName + "]", conn);
    conn.Open();
    OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd);
    DataTable dt = new DataTable();
    myDataAdapter.Fill(dt);
    //MessageBox.Show( dt.Rows.Count.ToString());
    MyDataGrid.Tag = dt.Rows.Count.ToString();
    MyDataGrid.DataSource = dt;
    OleDbCommand updateCmd = new OleDbCommand("UPDATE [" + SheetName + "]");
    myDataAdapter.UpdateCommand = updateCmd;
    conn.Close();
}

Here I'm hard coding the data into the table. This works.

DataTable dt = ((DataGridView)TC).DataSource as DataTable;


DataRow row0 = dt.NewRow();
row0["Name"] = "Jack";
row0["Status"] = "MISSING";
dt.Rows.Add(row0);

DataRow row1 = dt.NewRow();
row1["Name"] = "Mike";
row1["Status"] = "MISSING";
dt.Rows.Add(row1);

dgvThing.DataSource will give you the data that is bound to your DataGridView and you can minipulate this without modifying your original data source ie the excel file.

Edit: In this case, you would loop through the rows to find your person and update their status like so.

DataTable dt = ((DataGridView)TC).DataSource as DataTable;
foreach (DataRow row in dt.Rows)
{
    if (row["Name"].Equals("Jack"))
        row["Status"] = "Found";
}

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