Updating Datagridview data using SQLite Database - c#

I'm having trouble updating data from a data grid view with the use of a button. The text is editable but the changes does not save to the SQLite database. any ideas?
private void ProjectsAdmin_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'seniorProjectsDataSet2.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.seniorProjectsDataSet2.DataTable1);
}
private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1 || e.ColumnIndex != 3) //ignore header row and any column that doesnt have file name
return;
var filename = dataGridView1.CurrentCell.Value.ToString();
if (File.Exists(filename))
Process.Start(filename);
}
private void updateData_Click(object sender, EventArgs e)
{
SQLiteConnection conn = new SQLiteConnection();
dataGridView1.EndEdit();
dataTable1TableAdapter.Adapter.Update(seniorProjectsDataSet.Tables[0]);
for (int i = 0; i < seniorProjectsDataSet.Tables[0].Rows.Count; i++)
{
seniorProjectsDataSet.Tables[0].Rows[i].AcceptChanges();
}
}
}
}

I solved the problem without a Button. In the following code I´ll give you a example how the connection and the update works with a mysql-database (update in runtime):
CODE
DataTable dt = null;
DataGridView dgv1 = null;
If the form load you have to set your dt variable to a new datatable:
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select *from try.data ;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv1 = new DataGridView();
dgv1.AllowUserToAddRows = false;
dgv1.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv1.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv1.Dock = DockStyle.Fill;
dgv1.DataSource = dt;
this.Controls.Add(dgv1);
}
You have to set two events: CellValidating
private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
InitializeComponent();
if (e.ColumnIndex == 0)
{
dgv1.CancelEdit();
}
}
and the CellValidating Event:
private void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["Eid"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value + "";
string sql = string.Format("UPDATE `try`.`data` SET `{0}` = '{1}' WHERE Eid = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("datasource=localhost;port=3306;username=root;password=1234"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
This aktually works with MySql but in Sql are "Equal" components like the SqlConnection or the SqlCommand... I hope this solve you problem. Have a nice day!

using System.Data.SQLite;
SQLiteConnection con = new SQLiteConnection("Data Source=C:\\Cogs\\bin\\Release\\db\\my_database_file.db");
SQLiteCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from [my_table]";
con.Open();
cmd.ExecuteNonQuery();
DataTable dta = new DataTable();
SQLiteDataAdapter dataadp = new SQLiteDataAdapter(cmd);
dataadp.Fill(dta);
dataGridView1.DataSource = dta;
con.Close();

Related

How to Update Database using Datagrid in WPF

I would like to update Database when any Cell is updated in the GridView on particular button click.
Database connection
private void databaseBindingToGrid()
{
connetionString = #"initial catalog = Test; integrated security = SSPI; data source = KITS13AUG2019-I\JAGDEESH_SQL;";
conSql = new SqlConnection(connetionString);
conSql.Open();
cmd = new SqlCommand();
cmd.CommandText = "Select * from AGENTS";
cmd.Connection = conSql;
adpt = new SqlDataAdapter(cmd);
dt = new DataTable("AGENTS");
adpt.Fill(dt);
datGridView.ItemsSource = dt.DefaultView;
}
I tried like this but not working
private void C1ToolbarButton_Click(object sender, RoutedEventArgs e)
{
adpt.Update(dt);
MessageBox.Show("Updated");
}
You must declare a connection class which is return your connection open.
public SqlConnection Connection()
{
connetionString = #"initial catalog = Test; integrated security = SSPI;
data source = KITS13AUG2019-I\JAGDEESH_SQL;";
conSql = new SqlConnection(connetionString);
conSql.Open();
return conSql;
}
After that you declare Datagridview elements in your form load action.
public void FillDataGridView()
{
cmd = new SqlCommand();
cmd.CommandText = "Select * from AGENTS";
cmd.Connection = Connection();
adpt = new SqlDataAdapter(cmd);
dt = new DataTable("AGENTS");
adpt.Fill(dt);
datGridView.ItemsSource = dt.DefaultView;
}
And now you can use
private void C1ToolbarButton_Click(object sender, RoutedEventArgs e)
{
//it is call your data grid view when you click button
FillDataGridView();
}

Move to next Row in dataGridView

I am trying to develop a form which will search the database for the entered name. save the selected row and then move to the next one. but when i search again it clears the previously saved row.
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(datatable);
DV.RowFilter = string.Format("proName LIKE '%{0}%'", textBox1.Text);
dataGridView1.DataSource = DV;
}
private void Form1_Load(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand("select * FROM productDetails",connection);
DataSet dataset = new DataSet();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Zimad\Desktop\project1.accdb";
connection.Open();
dataAdapter.SelectCommand = command;
dataAdapter.Fill(datatable);
dataGridView1.DataSource = datatable;
connection.Close();
nRow = dataGridView1.CurrentCell.RowIndex;
}
private void button1_Click(object sender, EventArgs e)
{
if (nRow < dataGridView1.RowCount)
{
dataGridView1.Rows[nRow].Selected = false;
dataGridView1.Rows[++nRow].Selected = true;
}
}
button1 is used to save the selected row.
#Fabio is right. What i did here is that i loaded the search results in a textbox and later loaded the information against the item in the dataGridView
private void textBox1_TextChanged(object sender, EventArgs e)
{
listBox1.Visible = true;
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * FROM ProductDetails";
OleDbDataReader reader = command.ExecuteReader();
listBox1.Items.Clear();
while (reader.Read())
{
if (reader["proName"].ToString().Contains(textBox1.Text))
{
listBox1.Items.Add(reader["proName"].ToString());
}
}
connection.Close();
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * FROM ProductDetails";
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader["proName"].ToString().Contains(textBox1.Text))
{
dataGridView1.Rows.Add();
dataGridView1[0, 0].Value = reader["proName"].ToString();
}
}
connection.Close();
}

How to display SQL search results in a datagrid using WPF

private void Button_Click(object sender, RoutedEventArgs e)
{
SqlConnection sc = new SqlConnection();
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
string sql;
{
sql = "SELECT FROM WolfAcademyForm WHERE [Forename] == 'txtSearch.Text';";
{
grdSearch.ItemsSource = sql;
sc.Close();
}
This is the code that I have, When I press the search button nothing shows up... Can someone please help me with this problem, I don't get any errors
Problems:
SQL query is not right:
It should be like SELECT * FROM TABLENAME.
In WHERE clause [Forename] == 'txtSearch.Text', == should = and Textbox value should be concatenated using +.
Fixed Code:
private void Button_Click(object sender, RoutedEventArgs e)
{
string sConn = #"Data Source=MYDS;Initial Catalog=MyCat;
User ID=MyUser;Password=MyPass;";
using(SqlConnection sc = new SqlConnection(sConn))
{
sc.Open();
string sql = "SELECT * FROM WolfAcademyForm WHERE [Forename]= #Forename";
SqlCommand com = new SqlCommand(sql, sc);
com.Parameters.AddWithValue("#Forename", txtSearch.Text);
using(SqlDataAdapter adapter = new SqlDataAdapter(com))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}
}
}
Use this
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT FROM WolfAcademyForm WHERE [Forename] == " + txtSearch.Text + ";"
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("Employee");
sda.Fill(dt);
grdSearch.ItemsSource = dt.DefaultView;
}

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().

Calendar to DataGrid

I really can't seem to nail down what I need to accomplish my task. I have a DataGrid in asp.net in VS2010 this displays data from a SQL database , in one of these fields is a "StartDate".
Also I have a simple Calendar running . What I would like is to be able to update my DataGrid by passing it the selected date and using that as the "StartDate" to call a selection on the DataGrid , so only records with that start date will appear.
I have looked on-line but the examples are very old or are a bit confusing .
If anyone can layout the steps (if possible sample code) involved to achieve this i would be grateful or any resources or examples you have come across though I have searched for a while, hence the post!.
Thanks.
What i have currently is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{
// CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC88;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
}
protected void CalendarDRender(object sender, System.Web.UI.WebControls.DayRenderEventArgs e)
{
// If the month is CurrentMonth
if (!e.Day.IsOtherMonth)
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
if ((dr["Start"].ToString() != DBNull.Value.ToString()))
{
DateTime dtEvent = (DateTime)dr["Start"];
if (dtEvent.Equals(e.Day.Date))
{
e.Cell.BackColor = Color.PaleVioletRed;
}
}
}
}
//If the month is not CurrentMonth then hide the Dates
else
{
e.Cell.Text = "";
}
}
private void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
myda = new SqlDataAdapter("Select * from Bookings where Start ='" + Calendar1.SelectedDate.ToString() + "'", mycn);
dsSelDate = new DataSet();
myda.Fill(dsSelDate, "AllTables");
if (dsSelDate.Tables[0].Rows.Count == 0 )
{
GridView1.Visible = false;
}
else
{
GridView1.Visible = true;
GridView1.DataSource = dsSelDate;
GridView1.DataBind ();
}
}
}
What am i doing wrong?.
EDIT__
Finally it works , Here is my code if anyone has similar issue/requirement.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=BBC-PC-S054683;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
else
{ // CalendarChange();
Calendar1.VisibleDate = DateTime.Today;
strConn = #"Data Source=PC-Name;Initial Catalog=Bookings;Integrated Security=True";
mycn = new SqlConnection(strConn);
myda = new SqlDataAdapter("Select * FROM Bookings", mycn);
myda.Fill(ds, "Table");
}
BindGrid();
}
}
private DataTable GetRecords()
{
SqlConnection conn = new SqlConnection(strConnection);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from Bookings";
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
DataSet objDs = new DataSet();
dAdapter.Fill(objDs);
return objDs.Tables[0];
}
public void Calendar1_SelectionChanged(object sender, System.EventArgs e)
{
String Date = Calendar1.SelectedDate.ToLongDateString();
SqlConnection con = new SqlConnection(strConnection);//put connection string here
SqlCommand objCommand = new SqlCommand("SELECT * FROM Bookings where Date = '" + Date + "'", con);//let MyTable be a database table
con.Open();
SqlDataReader dr = objCommand.ExecuteReader();
GridView.DataSource = dr;
GridView.DataBind();
}
You need to filter your DataGridView.
try
{
myDataSet = new DataSet();
myDataSet.CaseSensitive = true;
DataAdapter.SelectCommand.Connection = myConnection;
DataAdapter.TableMappings.Clear();
DataAdapter.TableMappings.Add("Table", "TableName");
DataAdapter.Fill(myDataSet);
myDataView = new DataView(myDataSet.Tables["TableName"], "TIMESTAMP >= '" +
Convert.ToDateTime(fromDate) + "' AND TIMESTAMP <= '" +
Convert.ToDateTime(toDate) + "'", "TIMESTAMP", DataViewRowState.CurrentRows);
dgv.DataSource = myDataView;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
TIMESTAMP is a column in my DataGridView.
Note: This is just a code snippet!

Categories