Gowtham Ramamoorthy
Gowtham Ramamoorthy

Reputation: 896

Update not working from grid view (not able to get the error )

I'm trying to update a table from the gridview of tool to the SQL database. The problem is it's not getting updated in the database.

Below is my code for the button click which updates the database: while debugging the code i found that the data table DT is fetching only the source values not the updated one in the grid view....

Is there any property in the grid view which accepts these change and updates the DT table ?

    public partial class BusinessRules : Form
    {
    //Declaration Part
    private SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=AnimalProductsCoSD;Integrated Security=True");

    private string sqlconn;  // query and sql connection

    private SqlDataAdapter SDA = new SqlDataAdapter();

    DataTable DT = new DataTable();
    SqlCommandBuilder scb = new SqlCommandBuilder();

   private void button_retreive_Click(object sender, EventArgs e)
    {

        string commandText = "CoSD.RetreiveBusinessRulesTool";
        SqlCommand cmd = new SqlCommand(commandText, con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@BusinessType", SqlDbType.NVarChar, 60).Value = comboBox_BusinessType.Text;
        cmd.Parameters.Add("@CommodityGroup", SqlDbType.VarChar, 60).Value = comboBox_group.Text;
        try
        {

            con.Open();
            SDA.SelectCommand = cmd;
            DT = new DataTable();
            SDA.Fill(DT);
            int count1 = DT.Rows.Count;
            if (DT.Rows.Count > 0)
            {
                dataGridView.DataSource = DT;
                dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
                dataGridView.Columns[0].ReadOnly = true;           
            }
            else
            {
                MessageBox.Show("No Business Rules Found");


            }
        }
        catch (SqlException ex)
        {
            MessageBox.Show("Error : " + ex.Message);
        }
        finally
        {
            con.Close();
        }

    }

private void button_update_Click(object sender, EventArgs e)
    {
        try
        {
            if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                scb = new SqlCommandBuilder(SDA);
                SDA.Update(DT);
                // confirm
                MessageBox.Show("Updates successfully submitted to CoSD");

            }

            else
            {
                return;
            }

        }

        catch (Exception ex)
        {
            MessageBox.Show("Error : " + ex.Message);
        }


}   

Upvotes: 0

Views: 235

Answers (1)

David Kluszczynski
David Kluszczynski

Reputation: 39

In the try, put this

 scb = new SqlCommandBuilder(sda);
            sda.Update(dt);

In your initializer call

  SqlDataAdapter sda= new SqlDataAdapter("SELECT * FROM someWhere", connectionString);
    DataTable dt = new DataTable();

The problem is that you refresh the datagridview before submitting the changes, thus deleting anything inputted

**** EDIT ****

This is exactly what my code in a project I did a little while back looks like:

namespace TowerSearch
{
    public partial class EditParts : Form
    {
        const string conString = ConString.conString;
        static DataClasses1DataContext PartsLog = new      DataClasses1DataContext(conString);
        static Table<Part> listOfParts = PartsLog.GetTable<Part>();

        SqlDataAdapter sda;
        SqlCommandBuilder scb;
        DataTable dt;

        public EditParts()
        {
            InitializeComponent();
        }

        //Load and refresh the dataGridView
        private void showData()
        {
            SqlConnection con = new SqlConnection(conString);
            sda = new SqlDataAdapter("SELECT * FROM Parts", con);

            dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.DataSource = dt;
        }

        private void EditParts_Load(object sender, EventArgs e)
        {
           showData();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                dataGridView1.Refresh();
                scb = new SqlCommandBuilder(sda);
                sda.Update(dt);

                MessageBox.Show("Saved");
                showData();
            }
            catch (Exception ee)
            {
                MessageBox.Show("There is an error in the data!\nCheck if there are any blank spots besides Quantity.");
            }  
        }
    }
}

That definitely works, so try the code with the show data. I'd suggest just copying it verbatim first to see if it would work.

**** EDIT 2 ****

Another thing that you could try if you haven't managed to get it already is add a bindingSource. To do this, drag a bindingSource onto your dataGridView and then set the DataSource option to the table of the DB that you wan't to display

Hope that helps!

Upvotes: 1

Related Questions