在C#的DataGrid中直接修改数据。 private void dgvBind()
{
SqlConnection mycon = GetConnection();
try
{
mycon.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from mytable001", mycon);
DataTable table = new DataTable();
sda.Fill(table);
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = table;
this.dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
mycon.Close();
}
}
private void Form1_Load(object sender, EventArgs e)
{
dgvBind();
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
SqlConnection mycon = GetConnection();
try
{
mycon.Open();
string mystr1=dataGridView1.Columns[e.ColumnIndex].HeaderText "=" "'" dataGridView1.CurrentCell.Value.ToString() "'";
string mystr2=dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
string updateSql = "update mytable001 set " mystr1 " where id=" mystr2;
SqlCommand mycom = new SqlCommand(updateSql, mycon);
mycom.ExecuteNonQuery();
dgvBind();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
mycon.Close();
}
}
}
评论