如何使用C#中的数据表更新SQL表中的数据 [英] How to update data present in SQL table using data table in C#

查看:98
本文介绍了如何使用C#中的数据表更新SQL表中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我开发了ac#windows表单应用程序,它将从SQL表中获取特定数据并显示数据表格中的数据网格视图。



例如,有一个c#形式的文本框。如果用户填写了他需要的文本框,它将获取用户输入字段的特定数据并将其显示在数据网格视图中。



现在如果用户获得了他需要的数据,但他想要更改表中的数据。那么我们如何从数据网格视图更新表。我的意思是如果用户获得如下数据: -



客户ID名称出生年份

1250 Chaitanya 1982



现在用户想要更改客户ID,他只想输入1350代替1250并点击一个按钮然后它应该在sql表中更新。可能吗?我可以知道我们怎么做。



我尝试过:



使用(新的SqlCommandBuilder(适配器))

{

试试

{

DataTable dtPrimary = new DataTable();



adapter.Fill(dtPrimary);



//这将是你确定的记录更新:

dtPrimary.Rows [1] [pv_name] =value;



sqlConn.Open();

adapter.Update(dtPrimary);

sqlConn.Close();

}





但这个值应该在这里的代码中手动给出,我需要在单击按钮时在datagridview中输入的值应该在sql表中更新

Hi,

I have developed a c# windows forms application which will get particular data from an SQL table and displays the data in the data grid view in the form.

For example, there is a textbox in c# form. If a user fills the text box with what he needs, it will get the particular data of the user entry field and display it in the data grid view.

Now if a user got the data what he needs, but he want to change the data in the table. then how can we update the table from the data grid view. I mean if a user gets data as like below:-

Customer id name Year of birth
1250 Chaitanya 1982

Now the user want to change the customer id, he just want to type 1350 in place of 1250 and clicks a button then it should update in the sql table. Is it possible? may i know how can we do that.

What I have tried:

using (new SqlCommandBuilder(adapter))
{
try
{
DataTable dtPrimary = new DataTable();

adapter.Fill(dtPrimary);

// this would be a record you identified as to update:
dtPrimary.Rows[1]["pv_name"] = "value";

sqlConn.Open();
adapter.Update(dtPrimary);
sqlConn.Close();
}


but the value should be given manually in the code here, i need the value which we enter in the datagridview should update in sql table when a button is clicked

推荐答案

如果您显示数据然后gridview然后您可以将更改的值保存在数据库中,因为您可以使用'CellValueChanged'事件

见下面的代码片段

If you show the data then gridview then you can save the changed value in database, for that you can use 'CellValueChanged' event
see below snippet
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e){
  if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){
    //your code goes here
  }
}



OR'CellEndEdit'也适用于你


OR 'CellEndEdit' will also works for you

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e){
  if(dataGridView1.Columns[e.ColumnIndex].Name == "Reference"){
    //your code goes here
  }
}



in above示例'reference'是示例的列名。

h打开它帮助


in above example 'reference' is the column name for an example.
hope it helps


这篇关于如何使用C#中的数据表更新SQL表中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆