问题
I tried to update selected rows in DataGridView, but the result is strange, it always missing a row or another. The problem is when I click btnSettled button to set the settled date, then click btnUpdate to update the database, the result seems ok, but after click btnRefresh to refresh the DGV, there is always a missing row. Is that the problem on UpdateCommand or foreach loop? Please help me to solve this problem. Thank you.
before click btnSettle
after click btnSettled and btnUpdate
after click btnRefresh
My code as follows:
DataTable dtTrx = new DataTable();
SqlDataAdapter daTrx = new SqlDataAdapter();
DataSet dsTrx = new DataSet();
public Form1()
{
InitializeComponent();
getData();
}
private void getData()
{
string strConn = "Data Source=.\\xpw;Initial Catalog=MyStock;Integrated Security=True;";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string sqlTrx = "SELECT TrxID, TrxDate,Ticker,Qty,Price,Type,AccID, SettledDate,BrokerUserID FROM Trx";
daTrx = new SqlDataAdapter(sqlTrx, conn);
SqlCommandBuilder cbTrx = new SqlCommandBuilder(daTrx);
daTrx.Fill(dsTrx, "trx");
conn.Close();
dtTrx = dsTrx.Tables["trx"];
dgvTrx.DataSource = dtTrx;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
daTrx.Update(dsTrx, "trx");
}
private void btnRefresh_Click(object sender, EventArgs e)
{
dsTrx.Clear();
daTrx.Fill(dsTrx, "trx");
}
private void btnSettled_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell c in dgvTrx.SelectedCells)
{
dgvTrx[7, c.RowIndex].Value = "2017/7/23";
}
}
回答1:
First of all you need start using parameterized SQL queries.
Secondly I don't see a problem with your code, but you try this :
private void btnSettled_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow r in dgvTrx.SelectedRows)
{
r.Cells["SettledDate"].Value = "2017/7/23"; //use the column name instead of column index
}
this.BindingContext[dgvTrx.DataSource].EndCurrentEdit();
//the above line is added to improve the solution
//as per the link mentioned in the accepted answer
}
The reason behind this approach is that now even if you change the column position, you won't have to re-write the code to match the changes
As you are using SelectedCells
, thus unless your mouse is dragged over to the last Cell
it won't be added in the SelectedCell
collection
Note: in r.Cells["SettledDate"].Value
I assumed the column name is SettledDate
回答2:
Finally I found the solution in :
Programmingly udpating selected rows misses the last one in dgv.DataSource.GetChanges()?
It only needs to end-edit the last row after foreach loop:
this.BindingContext[dgvTrx.DataSource].EndCurrentEdit();
Thanks again to @Nobody.
来源:https://stackoverflow.com/questions/45299537/updating-datagridview-selected-rows