Hi CSharpers, I am trying to crud my datagridview and SQL Server, something is wrong with my code, could anyone check and update my codeblock please. I used the adventureworks SQL database.
I first got an error that there aren't tables in the update, than I changed something in the coding and now I receive an error "The ConnectionString Property has not been Initialized".
I added a datasource directly to the datagridview tasks 'wizard', which generated a dataset, tableadaptermanager..., after this I drag and dropped the customer details table from the 'Data source explorer' on my datagridview, ran the application and I could see the info.
I added 3 buttons:
- a button to **update** the datagrid and database after I changed any existing information *or* after I added a row,
- a button to **delete** selected row(s),
- and a final button to undo any changes I did(deletion, change of info or insertion of row).
If you could check my queries and coding, it has taken all of my time and skills in this field till now ... I can't find out what's really missing. I have checked a lot of websites ... but can't figure it out. If you could read my code and adapt it so if works, thank you.
Thanks a lot for making this work for me, much appreciated.
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;
namespace WindowsFormsApplication1
{
public partial class FormAdventureCustomers : Form
{
SqlDataAdapter dar = new SqlDataAdapter();
SqlConnection con = new SqlConnection();
DataSet ds = new DataSet();
public FormAdventureCustomers()
{
InitializeComponent();
}
private void FormAdventureCustomers_Load(object sender, EventArgs e)
{
try
{
this.customerTableAdapter.Fill(this.adventureWorks2012DataSet.Customer);
con.Open();
}
catch (Exception error)
{
MessageBox.Show("ERROR" + error.Message);
}
}
private void UpdateBtn_Click(object sender, EventArgs e)
{
try
{
dar.UpdateCommand = new SqlCommand(@"UPDATE Customer SET StoreID WHERE CustomerID=1;", con);
dar.UpdateCommand.Parameters.Add("@CustomerID", SqlDbType.Int, 4, "CustomerID");
DataSet ds = new DataSet();
dar.TableMappings.Add("Customer", customerTableAdapter.ToString());
dar.Update(this.adventureWorks2012DataSet.Customer);
}
catch (Exception error)
{
MessageBox.Show("ERROR" + error.Message);
}
}
private void DeleteBtn_Click(object sender, EventArgs e)
{
try
{
dar.DeleteCommand = new SqlCommand(@"DELETE FROM Customer WHERE CustomerID = @CustomerID;", con);
dar.DeleteCommand.Parameters.Add("@CustomerID", SqlDbType.Int, 4, "CustomerID");
dar.TableMappings.Add("Customer", customerTableAdapter.ToString());
}
catch (Exception error)
{
MessageBox.Show("ERROR" + error.Message);
}
}
private void UndoBtn_Click(object sender, EventArgs e)
{
}
}
}