简体   繁体   English

如何在C#中使用datagridview将数据保存到数据库

[英]How to save data to database using datagridview in C#

Im trying to update my database by using datagridview there is no error but there are no changes made when i Click on Save button.Can you help me here.. Here is my code Thanks in advance. 我试图通过使用datagridview更新我的数据库,没有错误,但是当我单击“保存”按钮时没有进行任何更改。在这里可以帮我吗。这是我的代码,谢谢。 .

private void EditRecord_Load(object sender, EventArgs e) {
     LoadData();
}

void LoadData() {
    string query = "SELECT *FROM Record";
    SqlDataAdapter da = new SqlDataAdapter(query, con);
    SqlCommandBuilder sbuilder = new SqlCommandBuilder(da);
    DataTable dtable = new DataTable();
    da.Fill(dtable);
    BindingSource bsource = new BindingSource();
    bsource.DataSource = dtable;
    dgv.DataSource = bsource;
}

private void btnSave_Click(object sender, EventArgs e) {
    if (dgv.RowCount > 1) {
        for (int x = 0; x < dgv.RowCount - 1; x++) {
            if (dgv.Rows[x].Cells[0].Value.ToString() == "") {
                SqlCommand cmdSave = new SqlCommand("UPDATE tblRecord SET FName=@FName, Address=@Address, ContactNo=@ContactNo WHERE IdNo=@IdNo", con);
                {
                    cmdSave.Parameters.Add("@IdNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[0].Value;
                    cmdSave.Parameters.Add("@FName", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[1].Value;
                    cmdSave.Parameters.Add("@Address", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[2].Value;
                    cmdSave.Parameters.Add("@ContactNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[3].Value;
                }
                con.Open();
                cmdSave.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Updated!");
            }
        }
    }
    LoadData();
}

It should be 它应该是

private void btnSave_Click(object sender, EventArgs e) {
if (dgv.RowCount >= 1) {
    for (int x = 0; x < dgv.RowCount - 1; x++) {
        if (dgv.Rows[x].Cells[0].Value.ToString()!="" && dgv.Rows[x].Cells[0].Value!=null) {
            SqlCommand cmdSave = new SqlCommand("UPDATE tblRecord SET FName=@FName,   Address=@Address, ContactNo=@ContactNo WHERE IdNo=@IdNo", con);
            {
                cmdSave.Parameters.Add("@IdNo", SqlDbType.VarChar).Value =   dgv.Rows[x].Cells[0].Value.ToString();
                cmdSave.Parameters.Add("@FName", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[1].Value.ToString();
                cmdSave.Parameters.Add("@Address", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[2].Value.ToString();
                cmdSave.Parameters.Add("@ContactNo", SqlDbType.VarChar).Value = dgv.Rows[x].Cells[3].Value.ToString();
            }
            con.Open();
            cmdSave.ExecuteNonQuery();
            con.Close();
            MessageBox.Show("Record Updated!");
        }
    }
} 

The query in LoadData() function must have a space ' ' after the '*'. LoadData()函数中的查询必须在'*'之后有一个空格''。 It is also advised to use a try catch block on your update operation. 还建议在更新操作中使用try catch块。 Also instead of running select *, it is always preferred to select the needed columns like 同样,最好不要选择select *,而是选择所需的列,例如

select column1,column2 from myTable; 从myTable中选择column1,column2;

string query = "SELECT * FROM Record";

try{
     //open connection
     //Excecute your command
   }
 catch (SqlException ex)
   {
       //Log exception(ex)
       // throw ex
   }
 finally
   {
      // Check if connection not null then  close connection
   }

There is a much easier way to do this by using a command builder. 通过使用命令生成器,有一种更简单的方法来执行此操作。

As your binding the DataGridView to your DataTable, any changes in the DGV are reflected into the DataTable. 当您将DataGridView绑定到DataTable时,DGV中的任何更改都会反映到DataTable中。 Therefore, you can use a command builder to save changes back. 因此,您可以使用命令构建器来保存更改。

If you look at my example below, from giving the command builder the SELECT command, it can generate the other relevant commands it needs to perform, INSERT, UPDATE & DELETE. 如果您看下面的示例,则通过为命令构建器提供SELECT命令,它可以生成需要执行的其他相关命令INSERT,UPDATE和DELETE。

You just need to make sure that the DataTable is Public or accessible. 您只需要确保DataTable是Public或可访问的。

Use something like this on your btnSave_Click :- 在您的btnSave_Click上使用类似的方法:

using (SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["con"]))
{
    var adaptor = new SqlDataAdapter();
    adaptor.SelectCommand = new SqlCommand("SELECT * FROM [Record]", con);

    var cbr = new SqlCommandBuilder(adaptor);

    cbr.GetDeleteCommand();
    cbr.GetInsertCommand();
    cbr.GetUpdateCommand();

    try
       {
         con.Open();

         adaptor.Update(dtable);
         MessageBox.Show("Changes Saved","Information");

        }
     catch (SqlException ex)
        {
           MessageBox.Show(ex.Message, "SqlException Error");
        }
     catch (Exception x)
        {
           essageBox.Show(x.Message, "Exception Error");
        }

    } 

} }

暂无
暂无

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

相关问题 如何在C#中将DataGridView多行数据保存到MySQL数据库中 - How to save DataGridView multiple row data in to MySQL database in c# 如何将数据从DataGridView保存到数据库? C#Winforms - How to save data from a DataGridView into database? c# winforms c#将数据从datagridview保存到数据库 - c# save data from datagridview to database 如何将datagridview批量数据保存到sql数据库,而datagridview数据与图像绑定到c#中的SQL数据库 - how to save datagridview bulk data to sql database while the datagridview data binded with images to SQL database in c# c# - 如何为datagridview实现更新按钮并使用dataHandler类(数据访问类)将值保存到数据库 - how to implement update button for datagridview and save values to database using a dataHandler class(data access class) c# C#如何将文本框中的数据插入到datagridview,然后将datagridview数据保存到数据库中? - C# How to Insert data from text boxes to datagridview and then save the datagridview data into database? 如何使用C#将DataGridView数据插入Access数据库表中? - How to insert DataGridView data in to table of access database using c#? 如何使用C#将datagridview更新到数据库? - how to update datagridview to database using c#? 使用C#编辑DataGridview并将其保存在数据库表中 - To Edit the DataGridview and also save it in a database table using c# 如何将datagridview中导入的excel保存到数据库C# - how to save imported excel in datagridview to database C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM