C#: SqlCe Question, cannot update to database, but can read data - c#

This code reads and updates the form fine when I run the program, but it does not update when I edit the values in the datagridview and click update.
I am following a video tutorial series and this code does work in the video to update the table.
Question: Why does it not update when I edit the values in the datagridview?
using System.Data.SqlServerCe;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private SqlCeConnection conn; // Our Connection
private SqlCeDataAdapter da; // Data Adapter
private DataSet ds; // Dataset
private string sTable = "authors"; // Table Name
public Form1()
{
InitializeComponent();
InitData(); // Get the Data
dataGridView1.DataSource = ds;
dataGridView1.DataMember = sTable;
}
public void InitData()
{
try
{
// Instantiate the Connection
conn = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
// Instantiate a new DataSet
ds = new DataSet();
// init SQLDataAdapter with select command and connection
da = new SqlCeDataAdapter("SELECT id, name, email FROM " + sTable, conn);
// Automatically generates insert, update and delete commands
SqlCeCommandBuilder cmdBldr = new SqlCeCommandBuilder(da);
// Fill in the dataset view
da.Fill(ds, sTable);
}
catch (Exception excep)
{
MessageBox.Show("Exception: " + excep.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
da.Update(ds, sTable);
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
}
}
}
The program compiles, but the update command is not working to update the database on click of button1.

This may seem silly but have you checked that the user name you are using to connect has write permissions and not just read-only on the database?

Related

How do I get a datagridview to update from database on form load?

I'm fairly new to C# and coding in general. I've looked through similar questions and didn't have much luck fixing this.
I am making an app that stores Student details for attendance in tables, in a database. Currently when I run it, the details are added to the tables from textboxes. A button opens a separate form with a datagridview, but the details are not updated in this. If I rerun the application and open the second form, the datagridview has been updated. How do I get the datagridview to update based on information added to the table while the application is running?
This is the code that adds the details to the table
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\corry\Desktop\StudentAttendanceBurton\Attendance.mdf;Integrated Security=True";
sc.Open();
using (SqlCommand com = sc.CreateCommand())
{
com.CommandText =
"insert into BUS102(\n" +
" Name,\n" +
" [Student ID],\n" +
" Date)\n" +
"values(\n" +
" #prm_Name,\n" +
" #prm_Student_ID,\n" +
" #prm_Date)";
com.Parameters.Add("#prm_Name", SqlDbType.NVarChar, 50).Value = student.Name;
com.Parameters.Add("#prm_Student_ID", SqlDbType.Int).Value = student.StudentID;
com.Parameters.Add("#prm_Date", SqlDbType.SmallDateTime).Value = student.Date;
com.ExecuteNonQuery();
}
}
This is the code for the form that has the datagridview
public partial class AttendanceForm : Form
{
public AttendanceForm()
{
InitializeComponent();
}
private void bUS102BindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
this.Validate();
this.bUS102BindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.attendanceDataSet);
}
private void AttendanceForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'attendanceDataSet.BUS102' table. You can move, or remove it, as needed.
this.bUS102TableAdapter.Fill(this.attendanceDataSet.BUS102);
}
}
public partial class Form1 : Form {
private DataSet m_ds = new DataSet();
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
using (SqlConnection conn = new SqlConnection(#"Data Source=YOURSql;Initial Catalog=YOURDB;Integrated Security=True")) {
// set command
SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Open();
da.Fill(m_ds);
// bind data to dataGrid
dataGridView1.DataSource = m_ds.Tables[0];
// refresh Data
dataGridView1.Refresh();
conn.Close();
}
}
private void cmdChangeData_Click(object sender, EventArgs e) {
// add new row explicit
DataRow nr = m_ds.Tables[0].NewRow();
nr[0] = "0000";
nr[1] = "xxxx";
// add new row to DataSet (just in memory, NOT TO DB)
m_ds.Tables[0].Rows.Add(nr);
// Refresh Data
dataGridView1.Refresh();
}
}
You have to refresh datagridview
this.dataGridView1.Refresh();

Keep additional rows when DBConcurrencyException is raised

I made a simple application that displays data from a database in a DataGridView, users can add rows, delete rows, update values and save the changes.
Now, let's say User A modifies a value in row 8 and saves. User B adds 50 rows and wants to modify a cell in row 8 also. When user B saves, DBConcurrencyException occurs and all his work is lost.
Considering the way people will use this app, this scenario should not happen but there is still a small chance.
Is it possible to keep the added rows when the DBConcurrencyException is raised ? Or should I just tell the users to save as often as possible ?
Here is the relevant code :
private BindingSource bindingSource = null;
private SqlCommandBuilder commandBuilder = null;
string conStringLocal = "xxxxxxxxxxx";
SqlCommand command;
SqlDataAdapter dataAdapter;
DataTable dataTable = new DataTable();
public Form1()
{
InitializeComponent();
DataBind();
}
private void DataBind()
{
dataGridViewCND.DataSource = null;
dataTable.Clear();
string query = "SELECT * FROM myTable";
SqlConnection con = new SqlConnection(conStringLocal);
try
{
con.Open();
command = con.CreateCommand();
command.CommandText = query;
dataAdapter = new SqlDataAdapter(query, con);
commandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Fill(dataTable);
bindingSource = new BindingSource { DataSource = dataTable };
dataGridViewCND.DataSource = bindingSource;
this.dataGridViewCND.Columns["id"].Visible = false;
this.dataGridViewCND.Sort(this.dataGridViewCND.Columns["Date"], ListSortDirection.Ascending);
}
catch (Exception ex)
{
// GENERIC ERROR MESSAGE
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
dataGridViewCND.EndEdit();
dataAdapter.Update(dataTable);
DataBind();
// UPDATE SUCCESS MESSAGE
}
catch(DBConcurrencyException ex)
{
// CONCURRENCY ERROR MESSAGE
DataBind();
}
catch (Exception ex)
{
// GENERIC ERROR MESSAGE
DataBind();
}
}

DataBase not updating in C# when using service-based database

I'm trying to write a program for my exam. I have to use and work with database, i've written some code and encountered a problem. Database is not updating. When I execute my application everything works perfectly, I add some info and it appears in my dataGridView, but when I go to the table in database that i've been updating and select "Show table data", it's empty.
This is function that inserts data into my database.
static public void Insert(string _imonesPav, string _imonesKodas, string _sutartiesPradzia, string _sutartiesPabaiga)
{
try
{
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO Tiekejai VALUES (#ImonesPav, #ImonesKodas, #SutartiesPradzia, #SutartiesPabaiga)", connection);
command.Parameters.AddWithValue("#ImonesPav", _imonesPav);
command.Parameters.AddWithValue("#ImonesKodas", _imonesKodas);
command.Parameters.AddWithValue("#SutartiesPradzia", _sutartiesPradzia);
command.Parameters.AddWithValue("#SutartiesPabaiga", _sutartiesPabaiga);
command.ExecuteNonQuery();
}
catch (SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
And this is how i use it.
private void updateDatabase_Click(object sender, EventArgs e)
{
SQLFunkcijos.Insert(imonesVardas.Text, imonesKodas.Text, sutartPradzia.Text, sutartPabaiga.Text);
SQLFunkcijos.Refresh(this.dataGridView1);
}
Refresh function is used to update data in dataGridView in real time.
So the question would be, what am i doing wrnog? Why table in database is not updating.
P.S. I've tried all Copy to Output options, it works only with Copy if newer.
EDIT1: Refersh function.
static public void Refresh(DataGridView _dataGridView)
{
try
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * FROM Tiekejai", connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
_dataGridView.DataSource = dataTable;
}
catch(SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
EDIT2: Problem solved! I was just using bad connection string. Thanks for everyones help.

One instance of class can't do two functions at the same time

I'm working on ASP.NET web aplication. I'm making it to be MVC and i have a problem with controler class. When i want to populate a drop down list with elements from my SQL database, class is working but only one instance of class with just one drop down list. When i use one class to populate 2 or more drop down lists it doesn't work and VS is not raising any errors. The controler class works, and it can populate drop down list, but just only one drop down list when page is loaded. So to work i have to make an instance of controler class for every drop down list. Please, can someone explain to me why won't work...
this is my DbBroker:
public DataTable VratiKategorije()
{
DataTable kategorije = new DataTable();
using (cn)
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM KategorijaLeka", cn);
adapter.Fill(kategorije);
}
catch (Exception err)
{
//
}
}
return kategorije;
}
And this is my Controler class which is using DbBroker:
public void VratiKategorije(DropDownList ddlKategorije){
try
{
ddlKategorije.DataSource = dbB.VratiKategorije();
ddlKategorije.DataTextField = "Naziv";
ddlKategorije.DataValueField = "ID_Kategorije";
ddlKategorije.DataBind();
}
catch (Exception err)
{
//Handle the err
}
ddlKategorije.Items.Insert(0, new ListItem("", ""));
}
And this is on Load_Page():
protected void Page_Load(object sender, EventArgs e)
{
KontrolerLeka kl = new KontrolerLeka();
kl.VratiKategorije(kategorijaLeka);
}
I found what was the problem. Ok, so when you use using() function with adapter there is no closing connection to database so when same function is called it can't populate another drop down list because the connection from last drop down list function is not closed. Insted of that code in DbBroker i used this and it worked! "pokreniDBtransakciju()" use cn (sql connection string) and after taking Record Set from database the connection is closed using "cn.Close()" which solved all problems.
DbBroker:
public DataTable Uzmi()
{
DataTable dt;
dt = new DataTable();
SqlCommand sc = new SqlCommand();
try
{
sc.CommandText = "SELECT * FROM KategorijaLeka";
sc.Connection = pokreniDBTransakciju();
SqlDataReader reader;
reader = sc.ExecuteReader();
dt.Load(reader);
cn.Close();
}
catch (SqlException e)
{
Console.WriteLine("GRESKA!!!" + e);
return null;
}
return dt;
}

Display chart according to datagridview line using Visual C# 2010

I have a form with a read only datagrid view. As the user moves the cursor up and down the datagrid view lines I would like to display a graph that is related to the highlighted line. I tried to use DataGridView1_SelectionChanged event, but it never gets executed.
dataGridView1_CellContentClick_1 does the trick, but requires the user to click which I would like to avoid.
public partial class conf_results : Form
{
private DataSet ds = new DataSet();
private DataTable dt = new DataTable();
private NpgsqlDataAdapter da = new NpgsqlDataAdapter();
private NpgsqlCommandBuilder sBuilder = new NpgsqlCommandBuilder();
public conf_results()
{
InitializeComponent();
try
{
// PostgeSQL-style connection string
// Making connection with Npgsql provider
NpgsqlConnection conn;
conn = new NpgsqlConnection(Properties.Settings.Default.connString);
conn.Open();
string sql = "SELECT m.orig_code,m.sejtvonal,round_dbl(m.parm_b,2),round_dbl(m.parm_c,2),round_dbl(m.variance,2),round_dbl(100 /(2^(m.ic50 - 1)),2),m.toxic,m.meres_id, " +
"d.sejtvonal,round_dbl(d.parm_b,2),round_dbl(d.parm_c,2),round_dbl(d.variance,2),round_dbl(100 /(2^(d.ic50 - 1)),2),d.toxic,d.meres_id " +
"from vegyulet_curve m, vegyulet_curve d where m.assay_id=d.assay_id and m.orig_code=d.orig_code "+
"and m.sejtvonal='Mes-Sa' and d.sejtvonal='Dx5'";
da = new NpgsqlDataAdapter(sql, conn);
sBuilder = new NpgsqlCommandBuilder(da);
DataSet ds = new DataSet();
// filling DataSet with result from NpgsqlDataAdapter
//da.Fill(ds);
da.Fill(ds, "vegyulet_curve");
// since it C# DataSet can handle multiple tables, we will select first
dt = ds.Tables["vegyulet_curve"];
// connect grid to DataTable
dataGridView1.DataSource = ds.Tables["vegyulet_curve"];
conn.Close();
}
catch (Exception msg)
{
// something went wrong, and you wanna know why
MessageBox.Show(msg.ToString());
throw;
}
}
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
int i = dataGridView1.SelectedRows[0].Index;;
// I am rewriting the code to use the chart on the form,
// I was debugging, but I could ot get the control
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
//detailForm f = new detailForm(dataGridView1.Rows[e.RowIndex].Cells[11].Value.ToString(),
//dataGridView1.Rows[e.RowIndex].Cells[12].Value.ToString(),
//dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());
//this.AddOwnedForm(f);
//f.ShowDialog();
grafikon f = new grafikon(Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString()),
dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString(),
Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString()),
Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[14].Value.ToString()),
Convert.ToBoolean(dataGridView1.Rows[e.RowIndex].Cells[13].Value.ToString()));
this.AddOwnedForm(f);
f.ShowDialog();
}
}
You can use the event CellMouseEnter to avoid having the user click the cell/row.
But take note, that the event will be invoked for each cell and might cause some performance issue if the user moves the cursor horizontally. What you can do is declare a global variable to hold the current row index, and first check when the event is invoked to see if the row changed or not.

Categories