繁体   English   中英

C#如何将datagridview的currentrow复制到单个datarow?

[英]C# how to copy datagridview's currentrow to single datarow?

DataRow dr;
dr = ((dgv.DataSource) as DataTable).Rows[dgv.CurrentRow.Index];

dgv是winform上预定义的DataGridView。 博士总是单身。

找到上面的代码。 但这行不通。 因为CurrentRow.Index没有绑定到DataTable's Index 我认为将DataGridViewRow复制到DataRow是最简单的方法。 不可能吗

尝试此操作的原因是为了在更改dgv时更新到数据库或从数据库中删除。 对于本地dgv的远程数据库CRUD,任何其他更好的解决方案都应该很棒。

提前致谢。

您可以通过在数据库表中定义一个ID列来直接将datagridview链接到数据库表,而无需通过数据表(可以在datagridview中显示或不显示ID列),如下所示

后面的代码:

SqlCommand update = new SqlCommand();
update.connection = conn;    // conn is your SqlConnection to the server
update.parameters.add("@Id",[sqldbtype.int]).value=dgv.Rows[dgv.CurrentRow.Index].Cell[0]; // 0 is the cell index of the ID column
update.Commandtext="Delete from table where [ID]=@ID" // delete the selected row
conn.open();
update.ExecuteNonQuery();

SqlDataAdapter adapter = SqlDataAdapter("SELECT*FROM Table", conn);
conn.close();
Datatable table = new Datatable();
adapter.Fill(table);
dgv.Datasource = table.Items;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM