如何在不丢失当前选定行的情况下更新DatagridView

编程入门 行业动态 更新时间:2024-10-22 15:39:24
本文介绍了如何在不丢失当前选定行的情况下更新DatagridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

大家好,

有时候我需要更新或删除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

本文发布于:2023-11-02 14:43:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况下   如何在   DatagridView

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!