Updating table with SqliteDataAdapter - c#

I have a bit of an issue when it comes to updating view in datagridview. My function successfully deletes selected row from database but DataAdapter does not fill datatable dt. Function with the same structure works perfectly when adding rows.
private string ConString;
private SQLiteCommand cmd;
DataTable dt = new DataTable();
SQLiteConnection sql_con;
SQLiteDataAdapter DB;
// Function to delete rows
public void DeleteRow(string value)
{
string sqlStatement = "DELETE FROM Trades WHERE ID = " + value;
try
{
sql_con = new SQLiteConnection(ConString);
sql_con.Open();
cmd = sql_con.CreateCommand();
cmd.CommandText = sqlStatement;
cmd.ExecuteNonQuery();
DB = new SQLiteDataAdapter();
dt.Clear();
DB.Fill(dt);
}
finally
{
sql_con.Close();
}
}

Related

displaying data from data list

As per the instructions I have entered the following code to display my results through the use of a datalist but I have an issue with the parameter
name
here is the method code
public static DataTable GetSessionByName(string Session_name)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Config.GetConnectionStr();
conn.Open();
//Prepare SQL Command with parameter
string sql = "Select * from Session Where Session_name =
#Session_name";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("Session_name", Session_name);
// Create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd); //Create a DataTable that
will store the result of the query
DataTable dt = new DataTable(); // this will query your database and
return the result to your datatable
da.Fill(dt);
//Close connection and release the data adapter
conn.Close();
da.Dispose();
//return the Datatable return dt;
return dt;
}
and here is where I try to use the datalist
protected void btnSearch_Click(object sender, EventArgs e)
{
string SearchName = txtSearchName.Text;
DataTable dt = Class.GetSessionByName(Session_name);
dlSearch.DataSource = dt;
dlSearch.DataBind();
}
I am getting the session_name does not exist in the current context when I enter the code in the button

Change database connection and update datagridview

I'm trying to display the database records after changing connection string data source. Here's my code:
m_dbConnection = new SQLiteConnection("Data Source=" + connFile + "; Version=3; FailIfMissing=True; Foreign Keys=True;");
getTable("SELECT * FROM tbl_programs WHERE int_is" +
lastDisplayedBuild.ToString() +
"=1 ORDER BY txt_programName;");
And my global variables are:
private SQLiteConnection m_dbConnection;
private SQLiteDataAdapter sqliteDataAdapter = new SQLiteDataAdapter();
private DataTable dataTable = new DataTable();
private BindingSource bindingSource = null;
How can I display new records in datagridview?
used this function to
public DataTable getData(string sqlCommand)
{
DataTable dt = new DataTable();
using (var con = new SQLiteConnection { ConnectionString = "your connection string" })
{
using (var command = new SQLiteCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
con.Close();
con.Open();
command.CommandText = sqlCommand;
dt.Load(command.ExecuteReader());
}
return dt;
}
}
//Call to load your Data
public void loadData()
{
this.DatagridView.DataSource = getData("Command string here");
}

Can't retrieve data from SQL Database

I have a program that inserts some values from text boxes into database. The problem is that the values are stored successfully into db but I can't get them into my Data Grid View...here's the code:
public void LoadMuzee(DataGridView table)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;" + "Initial Catalog=lista_muzee;Integrated Security=SSPI;");
SqlCommand cmd = new SqlCommand("SELECT muzee.*, gen.gen_nume " +
"FROM muzee INNER JOIN gen " +
"ON muzee.muz_gen_id = gen.gen_id", conn);
SqlDataAdapter sa = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
sa.Fill(dt);
conn.Close();
sa.Dispose();
cmd.Dispose();
conn.Dispose();
table.DataSource = dt;
table.Columns["muz_id"].Visible = false;
table.Columns["muz_gen_id"].Visible = false;
}
public frmMuzee()
{
InitializeComponent();
LoadMuzee(dgvMuzee);
}
your not performing databind on your gridview which causes data not get binded into gridview
table.databind()

How to show Data in table?

I am a beginner in C# and using MS Visual Studio 2010. Ans my problem is I am inserting data through textbox in a table named as (tbl_employees) and saving it successfully.
After saving when I see the table the new inserted data is not showing in tbl_employee even after updating.
Here is my code for updating table
private void btnupdate_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDataAdapter da;
string sql = "SELECT * From tbl_employees";
da = new System.Data.SqlClient.SqlDataAdapter(sql , conString);
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataRow row = ds.Tables[0].Rows[inc];
dRow[1] = textBox1.Text;
dRow[2] = textBox2.Text;
MaxRows = MaxRows + 1; //to enable last row is still last row
inc = MaxRows - 1;
MessageBox.Show("Now Table is updated too. . . ");
}
Code with ease to understand and implement
Insert
private void Insert()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Insert into YourTable Select (#Val1,#Val2,#Val3)";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Update
private void Update()
{
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Update YourTable Set Field1=#Val1,Field2=#Val2,Field3=#Val3 Where YourPrimaryKey=#Key";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
command.Parameters.Add("#Val1",txt1.Text);
command.Parameters.Add("#Val2",txt2.Text);
command.Parameters.Add("#Val3",txt3.Text);
command.Parameters.Add("#Key",txt4.Text);
int i = command.ExecuteNonQuery();
con.Close();
}
}
}
Select
private DataTable Get()
{
DataTable dt = new DataTable();
using(SqlConnection conn = new SqlConnection(yourConnString) )
{
string qry = "Select * From YourTable";
using(SqlCommand command = new SqlCommand(qry,conn))
{
conn.Open();
command.CommandType= CommandType.Text;
using(var reader = command.ExecuteReader(CommandBehaviour.CloseConnection))
{
dt.Load(reader);
}
con.Close();
}
}
return dt;
}
So now you have a Get method that returns DataTable , now you need a grid to display that data. Quite simple.
ASP.Net
private void BindGrid()
{
gridview1.DataSource = Get();
gridView1.DataBind();
}
Winforms
Same as above except we need not call DataBind().

Saving DataTable to SQLite Database by Adapter.Update

I wrote SQLite wrapper class
like this
using System;
using System.Data;
using System.Data.SQLite;
namespace SuPOS.Sources
{
public class SQLITE
{
private SQLiteConnection con;
private SQLiteCommand cmd;
private SQLiteDataAdapter adapter;
public SQLITE(string databasename)
{
con = new SQLiteConnection(string.Format("Data Source={0};Compress=True;", databasename));
}
public int Execute(string sql_statement)
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = sql_statement;
int row_updated;
try
{
row_updated = cmd.ExecuteNonQuery();
}
catch
{
con.Close();
return 0;
}
con.Close();
return row_updated;
}
public DataTable GetDataTable(string tablename)
{
DataTable DT = new DataTable();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", tablename);
adapter = new SQLiteDataAdapter(cmd);
adapter.AcceptChangesDuringFill = false;
adapter.Fill(DT);
con.Close();
DT.TableName = tablename;
return DT;
}
public void SaveDataTable(DataTable DT)
{
try
{
Execute(string.Format("DELETE FROM {0}", DT.TableName));
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", DT.TableName);
adapter = new SQLiteDataAdapter(cmd);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(DT);
con.Close();
}
catch (Exception Ex)
{
System.Windows.MessageBox.Show(Ex.Message);
}
}
}
}
I retrive DataTable from Database by "GetDataTable"
and binding to control.itemsource in WPF such as DataGrid
I can add new row on DataGrid and save to Database properly
I can change any column and save to database properly
but the problem is,
when I insert new row to DataGrid and call "SaveDataTable" as usual
I can save properly.. then I change some column on that row
now when I use "SaveDataTable" it said like this picture
after this message appear,
when I call "SaveDataTable" it will always said like this picture
I know this is an old thread, but the extra code you wrote for your solution only works because it cancels out a bug in your code, where you set:
adapter.AcceptChangesDuringFill = false ; /* default is 'true' */
If you remove the above line, you no longer need to have the row accept the changes and your method becomes much cleaner:
public DataTable GetDataTable(string tablename)
{
DataTable DT = new DataTable();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", tablename);
adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(DT);
con.Close();
DT.TableName = tablename;
return DT;
}
finally, I found the solution.
the problem came from rowstate of each row after I call Fill(DataTable), every DataRow in DataTable after Fill have "Added" in RowState.
so I can't call "Update(DataTable)" because it will Insert every rows in DataTable to Database.
because of that, in my wrapper class I have to Delete all rows in Database before "Update(DataTable).
so, I have to change RowState in every DataRow after method Fill(DataTable) by "AcceptChanges" method.
public DataTable GetDataTable(string tablename)
{
DataTable DT = new DataTable();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", tablename);
adapter = new SQLiteDataAdapter(cmd);
adapter.AcceptChangesDuringFill = false;
adapter.Fill(DT);
con.Close();
DT.TableName = tablename;
foreach (DataRow row in DT.Rows)
{
row.AcceptChanges();
}
return DT;
}
public void SaveDataTable(DataTable DT)
{
try
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", DT.TableName);
adapter = new SQLiteDataAdapter(cmd);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(DT);
con.Close();
}
catch (Exception Ex)
{
System.Windows.MessageBox.Show(Ex.Message);
}
}
Now I don't have to Delete all row before Update, and the problem gone.

Categories