大家好,
有时候我需要更新或删除datagridview上的行但是现在我无法正确刷新,除非重新绑定它,所以我选择的行被丢失了到列表的第一个。
Some times i need to update or delete row on datagridview but for now i can not refresh the properly unless rebinding it , so my selected row is losed to the first of list.
谢谢
推荐答案
如果您已经设置了DataSource,那么您应该没问题,例如
If you have set the DataSource then you should be fine e.g. using System.Data; using System.Data.SqlClient; public class DataOperations { public DataTable LoadData() { var dt = new DataTable(); using (SqlConnection cn = new SqlConnection(Properties.Settings.Default.ConnectionString)) { string commandText = @" SELECT CustomerIdentifier ,CompanyName FROM Customers;"; using (SqlCommand cmd = new SqlCommand(commandText, cn)) { cn.Open(); dt.Load(cmd.ExecuteReader()); } } return dt; } }
表格代码
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { bs.RemoveCurrent(); } private BindingSource bs; private void Form1_Load(object sender, EventArgs e) { bs = new BindingSource(); DataOperations ops = new DataOperations(); bs.DataSource = ops.LoadData(); dataGridView1.DataSource = bs; } }如果您添加了没有数据源的行,例如
Same goes for if you have added rows without a data source e.g.
private void button1_Click(object sender, EventArgs e) { dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index); } private void Form1_Load(object sender, EventArgs e) { dataGridView1.Rows.Add(new object[] { "Karen", "Payne" }); dataGridView1.Rows.Add(new object[] { "Bill", "Payne" }); dataGridView1.Rows.Add(new object[] { "Carol", "Payne" }); }这两个例子是为了删除,但同样适用于更新,例如
The two examples are for removal but the same holds true for updates e.g.
private void button1_Click(object sender, EventArgs e) { if (!dataGridView1.Rows[dataGridView1.CurrentRow.Index].IsNewRow) { dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value = "Edited"; } } private void Form1_Load(object sender, EventArgs e) { dataGridView1.Rows.Add(new object[] { "Karen", "Payne" }); dataGridView1.Rows.Add(new object[] { "Bill", "Payne" }); dataGridView1.Rows.Add(new object[] { "Carol", "Payne" }); }
更多推荐
如何在不丢失当前选定行的情况下更新DatagridView
发布评论