简体   繁体   中英

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. .

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 '*'. It is also advised to use a try catch block on your update operation. Also instead of running select *, it is always preferred to select the needed columns like

select column1,column2 from myTable;

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. 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.

You just need to make sure that the DataTable is Public or accessible.

Use something like this on your 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");
        }

    } 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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