如何不使用SQL查询更新dataGridView中的数据



我试图在dataGridView中进行CRUD操作,而不使用SQL查询,只使用dataSet。deletecreate函数还可以,但我一直在讨论如何实现update

要求是当用户单击dataGridView中的数据单元格时,该单元格的所有数据将显示在已经创建的textBoxes的列表中,并且可以编辑或更新这些数据。字段的所有数据都可以更改,但该行的id必须保持不变。

我的想法是在单击单元格时使用dataGridView_CellContentClick。所有数据将显示在已创建的textboxes列表中。我们需要通过使用类成员变量来存储要编辑的行的id。但在最后一步中,我不知道如何将更新的数据分配给dataGridView的行。有人能解决这个问题吗?

这是我的代码:

public partial class Form1 : Form
{
// data set 
DataSet1 dSet;
// to get id of current row
int id;
public Form1()
{
InitializeComponent();
PersonInfoInit();
}
// udpate cell clicked data 
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
// get id of the row want to update
id = dtgView.CurrentCell.RowIndex;
UpdateData();
}
// update current cell clicked data helper function 
private void UpdateData()
{
if (dtgView.CurrentRow.Index != -1)
{
txtAge.Text = dtgView.CurrentRow.Cells[1].Value.ToString();
txtName.Text = dtgView.CurrentRow.Cells[2].Value.ToString();
txtEmail.Text = dtgView.CurrentRow.Cells[3].Value.ToString();
}
}
private void PersonInfoInit()
{
dSet = new DataSet1();
dSet.Tables["Person"].Rows.Add(new object[] { 1, "Kane", 23, "abc@gmail.com" });
dSet.Tables["Person"].Rows.Add(new object[] { 2, "Sam", 22, "abc@gmail.com"});
dSet.Tables["Person"].Rows.Add(new object[] { 3, "Hung", 24, "haha@naver" });
dSet.Tables["Person"].Rows.Add(new object[] { 4, "Tuan", 26, "blusPai@hanmail"});
dtgView.AutoGenerateColumns = true; // without this line, datatGridView will not display data
dtgView.DataSource = dSet.Tables["Person"];
}
private void btnAdd_Click(object sender, EventArgs e)
{
dSet.Tables["Person"].Rows.Add(new object[]
{
dSet.Tables["Person"].Rows.Count + 1, int.Parse(txtAge.Text), txtName.Text.Trim(), txtEmail.Text.Trim()
});
ClearText();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
// how can I assign updated data for the row? not Add newly
// dSet.Tables["Person"].Rows[id]. = new object[] {

// };
}
// delete current clicked cell data 
private void btnDel_Click(object sender, EventArgs e)
{
try
{
foreach (DataGridViewCell cell in dtgView.SelectedCells)
{
if (cell.Selected)
dtgView.Rows.RemoveAt(cell.RowIndex);
}
}
catch
{
MessageBox.Show("ERROR: can't remve this data");
}
MessageBox.Show("Removed data successfully.");
}

您可以使用人员对象的BindingList,只需添加、删除或修改该列表中的对象,而不是使用数据集。

private BindingList<Person> Persons = new BindingList<Person>();
....
private void PersonInfoInit()
{
this.Persons.Add(new Person() { Id = 1, Name = "Kane", Age = 23, Email = "abc@gmail.com" });
this.Persons.Add(new Person() { Id = 2, Name = "Sam", Age = 2, Email = "abc@gmail.com" });
this.dataGridView1.AutoGenerateColumns = true;
this.dataGridView1.DataSource = this.Persons;
}
...
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}

最新更新