Click here to Skip to main content
15,884,088 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I've tried a lot of things - I'm having difficulty trying to get any modifications or deletions made in the datagridview1 control to stick. As a result my code might look a bit messy but it's all here. For reference, button3 is supposed to be the save button, button2 is the refresh button, and button1 is the submit button. This is Windows Forms in C# and I am editing on MS VS 2013. I have several tabs here, two are relevant. On the audit tab is a BindingNavigator, the DataGridView, button2 (Refresh) and button 3 (Save). On the Add Entry tab, there are several field box controls, a datetime control, and button1 (Submit entry). Of all of the functions, the ones mapped to button2 and button1 work flawlessly. You can refresh, you can add new rows. You cannot, however, save any changes you make in DataGridView1, and that's my problem. Here's the code, please help me.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace LicenseInventoryManager
{
    public partial class MainWindow : Form
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        SqlDataAdapter da;
        DataSet ds;
        SqlConnection con;
        private SqlDataAdapter dataAdapter = new SqlDataAdapter();
        private void MainWindow_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'licenseInventoryMgrDataSet.LIMTable' table. You can move, or remove it, as needed.
            this.lIMTableTableAdapter.Fill(this.licenseInventoryMgrDataSet.LIMTable);
            // Bind the DataGridView to the BindingSource
            // and load the data from the database.
            dataGridView1.DataSource = lIMTableBindingSource;
            GetData("SELECT * FROM LIMTable");         
        }
         private void button1_Click(object sender, EventArgs e)
        {
            con = new SqlConnection("Data Source=data0;Initial Catalog=LicenseInventoryMgr;Integrated Security=True;Connect Timeout=0;Trusted_Connection=Yes");
            da = new SqlDataAdapter("insert into LIMTable(Software,Host,AssetTag,ActivationDate,LicenseNumber)values('"+comboBox1.Text + "','" + textBox1.Text + "','" + textBox2.Text + "','" + dateTimePicker1.Value.ToString("yyyy-MM-dd") + "','" + textBox3.Text + "')", con);
            ds = new DataSet();
            da.Fill(ds);
            MessageBox.Show("Entry was successfully submitted.");
        }
        private void button2_Click(object sender, EventArgs e)
        {
            // Reload the data from the database.
            GetData(dataAdapter.SelectCommand.CommandText);
        }    
        private void lIMTableBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            DataRow ThisDataRow =
                ((DataRowView)((BindingSource)sender).Current).Row;
            if (ThisDataRow.RowState == DataRowState.Modified)
            {
                lIMTableTableAdapter.Update(ThisDataRow);
            }
        }      
        private void button3_Click(object sender, EventArgs e)
        {
            //updating values in grid...
            SqlConnection con = new SqlConnection("Data Source=data0;Initial Catalog=LicenseInventoryMgr;Integrated Security=True");
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter("select * from LIMTable", con);
            SqlCommandBuilder build = new SqlCommandBuilder(adp);
            adp.Update(ds.Tables[0]);
            con.Close();   
        }
        private void GetData(string selectCommand)
        {
            try
            {
                // Specify a connection string. Replace the given value with a 
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.
                String connectionString =
                    "Integrated Security=SSPI;" +
                    "Initial Catalog= LicenseInventoryMgr ;Data Source=data0";

                // Create a new data adapter based on the specified query.
                dataAdapter = new SqlDataAdapter(selectCommand, connectionString);

                // Create a command builder to generate SQL update, insert, and
                // delete commands based on selectCommand. These are used to
                // update the database.
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                // Populate a new data table and bind it to the BindingSource.
                DataTable table = new DataTable();
                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                dataAdapter.Fill(table);
                lIMTableBindingSource.DataSource = table;

                // Resize the DataGridView columns to fit the newly loaded content.
                //dataGridView1.AutoResizeColumns(
                   // DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
Posted
Updated 10-Jun-13 19:48pm
v2
Comments
Richard C Bishop 10-Jun-13 10:18am    
Nothing you have tried is complete. You have skipped important steps. Delete everything you have and research how to accomplish each task individually. You are somewhat on the right track but need a bit more understanding of what you are trying to do.
PrissySC 10-Jun-13 13:21pm    
I would just use and fill a bindingsource. Fill the table and set to the bindingsource datasource. From there set the dgv datasource to the bindingsource. (OK, really, I would use linq2sql)

Read here ... http://msdn.microsoft.com/en-us/library/xzb1zw3x(v=vs.80).aspx

Make sure that you set the dgv properties as needed, ie datasource, datamember, etc.

Any-who, don't hard code your string!
CHill60 10-Jun-13 17:47pm    
And if button3 is supposed to be a save button, button is ... then give them names!
PrissySC 11-Jun-13 16:27pm    
I second this! (I so dislike fixing ambiguously named code. :( )
Sunasara Imdadhusen 11-Jun-13 1:46am    
do not post empty function or event code to increase page size.

do an onselectedindexchanged event.
 
Share this answer
 
I would think that you would need to start here in your Main Window Load function.
Below is what you might think about it changing to be better to your cause.

C#
   dataGridView1.DataSource = GetData(this.licenseInventoryMgrDataSet.LIMTable);
   lIMTableBindingSource = this.lIMTableTableAdapter.Fill(this.licenseInventoryMgrDataSet.LIMTable);
// Bind the DataGridView to the BindingSource
// and load the data from the database.
// Neither 'dataGridView1' nor 'lIMTableBindingSource' have been properly define and initialized.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900