Displaying data from local SQL Server CE database in a gridview C# - c#

I am working on a small application for personal use. It is about keeping some data readily available for me.
It just consists of a local database, functions to add, erase or modify 4 or 5 columns of data and displaying the table in a datagridview.
I have managed to add data to the table and I have managed to use a
SELECT * FROM mytable
statement to get the data and iterate through it but I want to bind the table to the datagridview.
Here is my current method of trying to bind the data:
private void button2_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM myTable";
SqlCeConnection conn = new SqlCeConnection(conString);
using (SqlCeDataAdapter adap = new SqlCeDataAdapter(query, conn))
{
//the adapter will open and close the connection for you.
DataTable dat = new DataTable();
adap.Fill(dat);
dataGridView1.DataSource = dat;
}
}
When I run this code it does not throw an exception and if I change the name of the table to something that does not exists then it causes an exception telling that the table does not exists so I know that it is fetching my table. It simply is not showing it.
Any ideas?
Thanks

Related

How to load the datagridview using OOP C#

I am a beginner at C# and .NET oop concepts. I want to load the datagridview. I don't know how to pass the data. What I tried so far I attached below.
I created a class std
public void get()
{
SqlConnection con = new SqlConnection("server =.; initial catalog=testdb; User ID=sa; Password=123");
string sql = "select * from std";
con.Open();
SqlCommand cm = new SqlCommand(sql, con);
SqlDataReader dr = cm.ExecuteReader();
while ( dr.Read())
{
string stname = dr["st_name"].ToString();
string nicnum = dr["nic"].ToString();
}
con.Close();
}
Form: I am getting data like this way
std ss = new std();
ss.get();
dataGridView1.Rows.Clear();
If I wrote like this way how to pass data into the datagridview columns? I am stuck in this area
It's easier like this:
public void FillGrid()
{
var dt = new DataTable();
var da = new SqlDataAdapter("select * from std", "server =.; initial catalog=testdb; User ID=sa; Password=123");
da.Fill(dt);
dataGridView1.DataSource = dt;
}
but if you're going to use such a low level method of database access you should consider adding a DataSet type of file to your project; visual studio will write all this code and more for you with a few mouse clicks, and it makes a good job of creating tables and adapters that are a lot easier to work with
you have made multiple mistakes. First you read data wirh dataraeader and in every iteration define two stname and nimnum variables like. So when loop ends variables are destroyed. You have to define data table and read data by dataraeader and and add them to it row by row. Or read by sqldataadapter and read it immediately and pass to datatable object.Finnaly you pass datatable as return object of function. Use this vala as datasource of datagridview property if I'm not wrong.

DataSet is not updated in visual studio 2010

I am new to visual studio-2010. I am trying to create an application which reads data from sql database and shows on datagrid. I implemented the code which I found on internet.
here is the sql_button_Click function
private void sql_button_Click(object sender, RoutedEventArgs e)
{
string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\jakkulv\\Downloads\\VS projects\\employee\\employee\\SampleDatabase.mdf';Integrated Security=True;Connect Timeout=30;User Instance=True";
string SQL = "select emp_id,first_name from employee";
SqlConnection conn = new SqlConnection(ConnectionString);
// open the connection
conn.Open();
//Create a SqlDataAdapter object
SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
// Call DataAdapter's Fill method to fill data from the
// Data Adapter to the DataSet
DataSet ds = new DataSet("employee"); //database table name is "employee"
ds.Clear();
adapter.Fill(ds);
// Bind data set to a DataGrid control
dataGrid1.ItemsSource = ds.DefaultViewManager;
if (ds.HasChanges(DataRowState.Added))
{
// New rows have been added to the dataset, add appropriate code.
MessageBox.Show("data set has changes");
}
else
{
MessageBox.Show("data set has no changes");
// No new rows have been added to the dataset, add appropriate code.
}
but when I execute the same it is showing the message box saying - "data set has no changes".
why dataset is not updated??How to update it??
Your code will always result in the message box with data set has no changes, since it doesn't have any changes.
The data is the same as when it comes from the database, and since you haven't modified it, removed any records or added any records, there are no changes.
Just as the MSDN docs say
Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows.
Try to modify it, and then call ds.HasChanges() and you'll see that it will return true.

Empty database table

I want to insert values in "Navn" row and "Varenr" row in the DB table, when I'm clicking on a button. I have following code:
private void button2_Click(object sender, EventArgs e)
{
using (SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"))
{
try
{
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
string col1 = textBox2.Text;
string col2 = textBox3.Text;
//generate sql statement
cm.CommandText = "INSERT INTO ProduktTable (Navn,Varenr) VALUES (#col1,#col2)";
//add some SqlParameters
SqlParameter sp_add_col1 = new SqlParameter();
sp_add_col1.ParameterName = "#col1";
//data type in sqlserver
sp_add_col1.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col1.Size = 20;
sp_add_col1.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col1);
//in your insert into statement, there are how many parameter, you must write the number of parameter
SqlParameter sp_add_col2 = new SqlParameter();
sp_add_col2.ParameterName = "#col2";
//data type in sqlserver
sp_add_col2.SqlDbType = SqlDbType.NVarChar;
//if your data type is not number,this property must set
//sp_add_col2.Size = 20;
sp_add_col2.Value = textBox2.Text;
//add parameter into collections
cm.Parameters.Add(sp_add_col2);
//open the DB to execute sql
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
But unfortunately, my data table is still empty:
I have set a breakpoint on the ExecuteNonQuery function, and it is triggered, when pressing on the button:
My table definition:
Your connection string is causing this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True"
|DataDirectory| Your database that is being updated in this method is in your App Data Directory while the one you are trying to retrieve data from is in your project folder...
|DataDirectory| is a substitution string that indicates the path to the database. DataDirectory also makes it easy to share a project and also to deploy an application. For my PC my App Data Directory is:
C:\Users\MyUserName\AppData\...
If you browse to this location and then go to following folders
...\Local\Apps\2.0\Data
You will be able to find your particular application directory probably stored with your assembly name, or some hash when you go there you will find it the database there is being updated just fine. This connection string is best for deployment.
You can also try this:
If you notice that Server Explorer is detecting all the databases on my PC and you can notice that there are couple of MINDMUSCLE.MDF files but all are at different paths, this is because there is one file in DEBUG directory, one in my PROJECT directory, one in my APP DATA directory. The ones starting with the numbers are stored in my APP DATA directories... If you select your respective database file and then run the SELECT query against it, you will get your data.
I made a tutorial some time ago. May be it will help you:
Check the value that ExecuteNonQuery is returning. It should return an int with the number of records affected by the SQL statement.
If it comes back with a value other than 0, then you know a record is being inserted somewhere. Before you close the connection, run a SQL query against the table to select all of the records and see if they come back through the code.
SELECT * FROM ProduktTable
If you get some records, then you may want to double check the database you're looking at through the IDE and the one your inserting records into through the code. It could be possible that you've got two different databases and you're querying one while inserting into another one.
Those are the steps that I would go through to help narrow down the issue and sounds like something I've probably done before. I hope it helps!

I cannot update an Access 2007 table using C# statements

I'm trying to add records to a MS Access table 2007 using a C# application. My table consists of 3 fields: ID, Name and phone.
For example I tried to add a record for some one with these data: ID=1, Name=Boulis, and phone=1212422. The query didn't return any errors but I didn't find this data in my table.
But the most surprising matter is that when I tried to add the same previous data I got an error saying:
"The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again."
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection();
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\boulis.accdb;;Persist Security Info=False ";
con.ConnectionString = ConnStr;
con .Open();
MessageBox.Show("The connection is available now");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO info(ID, Name, phone) Values(#StudIDTxt, #StudNameTxt, #StudCNCITxt)";
cmd.Parameters.AddWithValue("#StudIDTxt",1);
cmd.Parameters.AddWithValue("#StudNameTxt", "boulis");
cmd.Parameters.AddWithValue("#StudCNCITxt", 1212422);
cmd.Connection = con;
cmd.ExecuteNonQuery();
MessageBox.Show("table is already updated");
}
The error message you receive on the second attempt clearly indicates that the first attempt was successful. If you already had the table open in Access before performing the INSERT in C# then you won't be able to see the new record until you either
close and re-open the table in Access, or
refresh the Datasheet View (or Form, or whatever). That can be accomplished by clicking the "Refresh All" button in the "Records" section of the "Home" tab (in Access 2010, anyway).

Realtime updating MDB database through a datagridview

I am currently trying to create a small program that takes the data from a MDB database that is displayed in a datagridview. The program should allow the user to modify (add, update, delete) the data in the datagridview. Furthermore everything should be updated to the MDB automatically (no buttons). I know there are a lot of topics out there regarding this subject, however for some reason I am unable to reproduce the same results.
I am able to retrieve the data from the MDB file and display it in the datagridview but I am unable to add, modify or delete data. The program keeps throwing exceptions at me but I don't understand why.
First the user has to create a database. The database is generated automatically by code.
private void CreateNewDatabase_Click(object sender, EventArgs e)
{
string DB_FILENAME = "c:\Test.mdb";
// GENERATE THE ACCESS FILES, ITS TABLES AND ITS COLUMNS
var cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0.;Data Source=" + DB_FILENAME; //Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly
var catType = Type.GetTypeFromProgID("ADOX.Catalog");
object o = Activator.CreateInstance(catType);
catType.InvokeMember("Create", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { cnnStr });
OleDbConnection cnn = new OleDbConnection(cnnStr);
cnn.Open();
var cmd = cnn.CreateCommand();
// CREATE SCHEDULE TABLE
cmd.CommandText = "CREATE TABLE SCHEDULE ([ID] IDENTITY PRIMARY KEY, [Day] TEXT, [Month] TEXT, [Year] TEXT, [IMS] TEXT, [Customer] TEXT, [Short Description] TEXT, [Long Description] TEXT, [Delivery Ticket Number] TEXT, [Returned] TEXT)";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO SCHEDULE ([ID]) VALUES (1)";
cmd.ExecuteNonQuery();
// DISPOSE OF THE VARIABLES USED
cnn.Close();
cnn.Dispose();
cmd.Dispose();
}
Once the database has been created it is used in a windows form with a datagridview in it.
public void Initialize()
{
Con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sttngs.DBloc);
Con.Open();
// TRY TO OPEN THE DATABASE FILE AND POPULATE THE DATAGRIDVIEW
da = new OleDbDataAdapter("SELECT [Day], [Month], [Year], [IMS], [Customer], [Short Description], [Long Description], [Delivery Ticket Number], [Returned] FROM SCHEDULE",Con); // WHERE [Returned] = '" + "NO' ", Con);
// POPULATE cBuilder
cBuilder = new OleDbCommandBuilder(da);
ScheduleData = new DataTable();
da.Fill(ScheduleData);
if (ScheduleData.Rows.Count > 0)
{
BindingSource BDS = new BindingSource();
BDS.DataSource = ScheduleData;
this.dataGridView.DataSource = BDS;
}
}
Once the data in the datagridview is changed (handled by the CellValidating event) the data should be updated in the MDB.
private void dataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (ScheduleData.GetChanges() != null)
{
dataGridView.EndEdit();
da.Update(ScheduleData);
ScheduleData.AcceptChanges();
}
}
The code is pretty straight forward but for some reason I am unable to figure out why the data in the MDB is not updated. I have been stuck for a while now so any help would be great!
One thing I can see that will cause an issue is that when you setup your commandbuilder you are not requesting the relevant UPDATE, DELETE & INSERT commands.
When you generate the command builder like this :-
cBuilder = new OleDbCommandBuilder(da);
Follow up with :-
cBuilder.GetUpdateCommand();
cBuilder.GetInsertCommand();
cBuilder.GetDeleteCommand();
You may need to declare all of this in Cell Validating, I'm unsure. Give It a try.
Look this MSDN article over, its for the SQLcommamdbuilder, but the same rules apply :-
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.aspx
Also, You have no open connection to the Data Adapter as you try to update it :-
if (ScheduleData.GetChanges() != null)
{
dataGridView.EndEdit();
//Open a connection Here
da.Update(ScheduleData);
ScheduleData.AcceptChanges();
}
Your SQL String is incorrect, try :-
"SELECT (Day, Month, Year, IMS, Customer, Short Description, Long Description, Delivery Ticket Number, Returned) FROM [SCHEDULE]"

Categories