I have a project of type Windows Forms i Visual Studio 2010 Express.
I have created a service based local database and am able to show its data in textboxes on my Form and skipping through each of the records with buttons “Next” and “Previous”. So I have a connection to the database.
However, when I want to update the database with a new record with data from the textboxes when I click the Button “SAVE”, the data are only stored in the dataset and showed in the textboxes when I reach their position with the buttons, but not stored in the database. The next time I open the application, the new “stored” record is therefore gone.
Any idea where the error is in my code? Thanks a lot.
Here is the code for my save button in the file Form1.cs:
private void btnSave_Click(object sender, EventArgs e)
{
DataRow row = ds.Tables[0].NewRow();
row[1] = textBox1.Text;
row[2] = textBox2.Text;
row[3] = textBox3.Text;
row[4] = textBox4.Text;
ds.Tables[0].Rows.Add(row);
try
{
objConnect.UpdateDatabase(ds);
MaxRows += 1;
inc = MaxRows - 1;
MessageBox.Show("Database updated");
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
btnCancel.Enabled = false;
btnSave.Enabled = false;
btnAddNew.Enabled = true;
}
And here is the code for my class DatabaseConnection:
class DatabaseConnection
{
private string sql_string;
private string strCon;
private SqlDataAdapter da_1;
public string Sql { set { sql_string = value; } }
public string connection_string { set { strCon = value; } }
public DataSet GetConnection { get { return MyDataSet(); } }
private DataSet MyDataSet()
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
da_1 = new SqlDataAdapter(sql_string, con);
DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_Data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
SqlCommandBuilder cb = new SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
Related
I want to display a datagrid that will return records based on a query from my search button but whenever I click the search button, it returns all the records from the database.
HTML
<html>
<asp:TextBox ID="ClientCode" runat="server"></asp:TextBox>
<asp:GridView ID="ClientDataGrid" runat="server" Height="111px"
Width="202px" Visible="False"></asp:GridView>
C#
private void rep_bind()
{
connection();
string query = ""select * from client where client_code ='" +
ClientCode.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
ClientDataGrid.DataSource = ds;
ClientDataGrid.DataBind();
}
private void InitializeComponent()
{
}
protected void search_Click(object sender, EventArgs e)
{
Label1.Text = "";
connection();
string query = string.Format("select * from client where client_code
='" + ClientCode.Text + "'") ; ;
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#category", SqlDbType.NVarChar, 20).Value =
category.SelectedItem.Text;
SqlDataReader dr;
dr = com.ExecuteReader();
ListItem selectedItem = category.SelectedItem;
if (string.IsNullOrWhiteSpace(ClientCode.Text) &&
string.IsNullOrWhiteSpace(ClientName.Text))
{
ClientDataGrid.Visible = false;
Label1.Visible = true;
Label1.Text = "Please Enter Correct Search Values";
}
else if (dr.HasRows)
{
dr.Read();
rep_bind();
ClientDataGrid.Visible = true;
}
else
{
ClientDataGrid.Visible = false;
}
}
I want to display records that will match the client code on the text box but it always return all the records from the database.
I'm unable to comment on the actual question so I'll ask it here.
You seem to be executing the same query twice. Once to see if it has any rows and the second time to fill the data grid. You can change this so that the query is executed only once.
One way to prevent SQL injection attacks is to use a Stored Procedure instead of directly creating the query using string interpolation. Use a stored procedure and pass your conditions using parameters.
Here's a link that explains how to create one
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/create-a-stored-procedure
How about this version?
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Stores";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
}
I am now working on a little project on school in WPF using SQLite. I have an SQLite table that has these fields: id (primary key), name, sex, station, job, and date. I have a DataGrid that has the sex, station, and job as ComboBoxes. When I save the data from my table in an ObservableCollection, then the data loading in the DataGrid works great. My problem is now when I want to modify the values from the DataGrid in the SQLite table. Any idea would be nice.
Here's what I tried so far.
public SQLiteConnection m_db = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
SQLiteDataAdapter adap;
DataSet ds;
DataTable dt;
SQLiteCommandBuilder cmdbl;
string Query;
public MainWindow()
{
InitializeComponent();
dataGrid.ItemsSource = Userss.GetValues();
ds = new DataSet();
dataGrid.BeginInit();
ds.Tables.Add(CreateTable());
dataGrid.DataContext = ds.Tables[0];
dataGrid.EndInit();
}
public DataTable CreateTable()
{
m_db.Open();
Query = "Select * from user";
adap = new SQLiteDataAdapter(Query, m_db);
dt = new DataTable();
adap.Fill(dt);
m_db.Close();
return dt;
}
private void Update_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("Are you sure you want to make those changes?", "Please confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
try
{
dt = dataGrid.DataContext as DataTable;
cmdbl = new SQLiteCommandBuilder(adap);
adap.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
this.dataGrid.CancelEdit();
}
When I press the Update button, the DB table remains the same.
The ObservableCollection works well.
Function getValues() from userss class
public static ObservableCollection<Userss> GetValues()
{
m_dd.Open();
string sql = "select * from user";
userCol.Clear();
SQLiteCommand cmd = new SQLiteCommand(sql, m_dd);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string sex1 = reader["sex"].ToString();
string station1 = reader["station"].ToString();
string job1 = reader["job"].ToString();
string data1 = reader["date"].ToString();
userCol.Add(new Userss()
{
Id = Convert.ToInt32(reader["id"]),
Name = reader["name"].ToString(),
Sex = (Sex)Enum.Parse(typeof(Sex), sex1),
Station = (Stations)Enum.Parse(typeof(Stations), station1),
Job = (Jobs)Enum.Parse(typeof(Jobs), job1),
Date = Convert.ToDateTime(data1)
});
}
m_dd.Close();
return userCol;
}
I have a datagrid that gets filled out with table data with a loadStudentTable() method.
I have search box in which i am trying to filter the dataGrid with values that contain.
It doesnt seem to be working. States the error:
Object reference not set to an instance of an object.
Search Text Change
private void SearchTxt_TextChanged(object sender, EventArgs e)
{
try
{
(studentGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("Student_FName LIKE '%{0}%'", SearchTxt.Text);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Student table load
//Fills out Student table
private void loadStudentTable()
{
SqlConnection conn2 = new SqlConnection(#"Data Source=(LocalDB)\v11.0; AttachDbFilename=C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\Student_CB.mdf ;Integrated Security=True");
conn2.Open();
try
{
SqlCommand cmdDatabase2 = new SqlCommand("Select * from Student", conn2);
SqlDataAdapter sda2 = new SqlDataAdapter();
sda2.SelectCommand = cmdDatabase2;
DataTable dbdataset2 = new DataTable();
sda2.Fill(dbdataset2);
BindingSource bSource2 = new BindingSource();
bSource2.DataSource = dbdataset2;
studentGridView.DataSource = bSource2;
sda2.Update(dbdataset2);
studentGridView.Columns[0].Width = 92;
studentGridView.Columns[1].Width = 200;
studentGridView.Columns[2].Width = 180;
studentGridView.Columns[3].Width = 180;
studentGridView.Columns[4].Width = 170;
studentGridView.Columns[5].Width = 170;
studentGridView.Columns[6].Width = 130;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn2.Close();
}
Loading the table is fine, its just the filtering to what input is used in the search text box.
Any ideas or help please.
Split your code as below and try..
private void SearchTxt_TextChanged(object sender, EventArgs e)
{
try
{
var bindData = (BindingSource)studentGridView.DataSource;
var dataTable = (DataTable)bindData.DataSource;
dataTable.DefaultView.RowFilter = string.Format(""Student_FName LIKE '%{0}%'", SearchTxt.Text);
studentGridView.Refresh();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a main form which has an Add Teacher button and an Add subject button which directs them to their respective forms.The add teacher button works perfectly fine but when i click the add subject button it shows error: Cannot find table at position 1.I have been following the same procedure in add subject button as i did in add teacher button .Also I first added tbl_teachers table and then tbl_subjects table in my database ,so technically tbl_teachers should have index 0 right?Also when i click the Data Source section I only see it has only tbl_teachers.How do I update the data source? Thanks in advance.
try
{
SubjectConnect = new DatabaseConnection();
conString = Properties.Settings.Default.teachersConnectionString;
SubjectConnect.connection_string = conString;
SubjectConnect.sql = Properties.Settings.Default.SQL2;
ds = SubjectConnect.GetConnection;
Maxrows = ds.Tables[1].Rows.Count;
}
catch (Exception err)
{
MessageBox.Show(err.Message,"error");
}
class DatabaseConnection
{
private string sql_string;
private string strCon;
SqlDataAdapter da_1;
public string sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public DataSet GetConnection
{
get { return MyDataset(); }
}
private DataSet MyDataset()
{
SqlConnection con = new SqlConnection(strCon);
con.Open();
da_1 = new SqlDataAdapter(sql_string, con);
DataSet dat_set = new DataSet();
da_1.Fill(dat_set,"Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(DataSet ds)
{
SqlCommandBuilder cb = new SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
I'm filling gridview from mysql table
public void Init()
{
DataSet dataset = new DataSet();
dataset = FillGrid();
bindingSorce.DataSource = dataset.Tables[0];
gridControl1.DataSource = bindingSorce;
}
public static DataSet FillGrid()
{
MySqlConnection newConnection = new MySqlConnection(_connectionString);
try
{
DataSet dataset = new DataSet();
newConnection.Open();
if (newConnection.State.ToString() == "Open")
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = newConnection;
cmd.CommandText = "SELECT * FROM main";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
adapter.Fill(dataset);
}
else
{
return null;
}
newConnection.Close();
return dataset;
}
catch { return null; }
}
After any changes I'm trying to update mysql table
private void gridView1_RowUpdated(object sender, EventArgs e)
{
try
{
BindingSource bs = (BindingSource)gridView1.DataSource;
DataTable changes = ((DataTable)bs.DataSource).GetChanges();
if (changes != null)
{
bool asd = UpdateGrid(changes);
((DataTable)((BindingSource)gridView1.DataSource).DataSource).AcceptChanges();
}
}
catch { }
}
public static bool UpdateGrid(DataTable datatable)
{
MySqlConnection newConnection = new MySqlConnection(_connectionString);
//try
{
newConnection.Open();
if (newConnection.State.ToString() == "Open")
{
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = newConnection;
cmd.CommandText = "SELECT * FROM main";
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
MySqlCommandBuilder cmb = new MySqlCommandBuilder(adapter);
//adapter.UpdateCommand = cmb.GetUpdateCommand();
//adapter.Update(datatable);
cmb.GetUpdateCommand();
adapter.Update(datatable);
}
else
{
return false;
}
newConnection.Close();
return true;
}
// catch { return false; }
}
And table realy updating, but if after that I'll call Init() then FillGrid() will return dataset with right columns, but without rows!(dataset.tables[0].Rows.count = 0). After restart programm filling will work true, but again updating will have the same effect
I started facing the same issue you post here after upgrading the version of MySQL database.
I have developed a C# application that querys a MySQL database and fills several datagrids using MySqlDataAdapter Fill() method. The database version in development environment was MySQL Server 5.1.38. When I installed the final database in the server, I used the latest release of the same version, MySQL Server 5.1.73.
When I started testing the application, I started getting exactly the same problem: whenever any change on the data was made via the datagrid, the database updated correctly, but after that, any datagrid in the application querying the database returned 0 rows. After searching on the web I found only two or three posts refering to the same issue, but with no answer. By now, the only way to get rid of it was uninstalling the upgrade 5.1.73 and installing the 5.1.38 version again.