In this tutorial, I'm going to show a fairly simple way to bind a .NET DataGridView to a database. The form designer has some support for data binding, but I found doing it without the form designer is a little easier to understand and implement. Also, when I'm developing a desktop database application, my database schemas are rarely 100% defined, and the form designer doesn't easily support changes to the database.
The database I'm going to use for the example code will be an Access database. I know Access databases aren't the preferred database type for developers - because of their speed and scalability. However, for simple database apps, Access is hard to beat - since you don't need to install any outside database engines. In reality, the concepts shown in this tutorial can be used with any number of databases.
The first thing we'll need to do is generate a connection string to connect to our Access database. For simplicity, the database I'm using doesn't require any authentication. If your database has authentication, MSDN has some great documentation on how to accomplish that.
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
The connection string is broken up into two parts, a provider and a data source. The provider is the engine we're going to be using - in this case, Microsoft's Jet engine. The data source, for Access, is simply the path to the database file.
Now let's use the connection string and get some data from our database.
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\myDatabase.mdb";
//create the database query
string query = "SELECT * FROM MyTable";
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
dAdapter.Fill(dTable);
To keep the code simple, I've left out a lot of error handling. You'll
definitely want to surround dAdapter.Fill with some exception
handling. That call will fail for many different reasons - for instance
the database isn't where the connection string says it is, or the query
string is invalid SQL code.
So let's go through what this code is actually doing. The first thing to
do is to create the connection string as described above. Then we need
an SQL statement to execute on our database. This can be any SELECT
statement you want. Next we create an
OleDbDataAdapter
which serves as a bridge between our DataTable and our database. An
OleDbCommandBuilder
comes next. This beautiful object automatically generates SQL insert,
update, and delete statements to rectify changes made to our
DataTable. Next we need to make a
DataTable
to hold the information retrieved from the database. And lastly, we call
dAdapter.Fill(dTable) which executes our SQL query and fills dTable
with the results.
Now that we have a DataTable filled with database information, let's
see how to synchronize it with a DataGridView.
//the DataGridView
DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dgView.DataSource = bSource;
The
BindingSource
object is what will be keeping our DataTable synchronized with the
DataGridView. So we set the DataSource of the BindingSource to
dTable, then set the DataSource of the DataGridView to the
BindingSource. Now when your program runs, the DataGridView should be
filled with the results of your SQL query.
At point, any changes made by the user in the DataGridView will
automically be made to the DataTable, dTable. Now we need a way to get
the changes back into the database. All you have to do is call the
Update function of the OleDbDataAdapter with the DataTable as the
argument to accomplish this.
dAdapter.Update(dTable);
This call will use the OleDbCommandBuilder to create all of the
necessary SQL code to synchronize your database with the changes made to
dTable. But, when should you call this function? There's lots of
different answers to that. If you have a save button, call it when the
user pushes save. If you want the database updated in real-time, I like
to call it on the DataGridView's Validating event.
The last topic to discuss is error handling. What happens when the user
types something in the DataGridView that can't be put in the database -
like text where a number is supposed to go? Because you're using
DataBinding, it would take a lot of work to get the data type at each
column and manually make sure the user typed in the correct thing.
Fortunately, the DataGridView has an event,
DataError,
to handle that for you. Whenever the user enters something incorrectly,
this event will be fired. From this event you can get the row and column
index of the cell where the incorrect value was placed, and you can also
cancel the event so you don't attempt to update the database with bad
data.
That's all the code required to perform two-way data binding with an Access database.
How can i restict to type text in a datagridview cell and alow only numerical data.
The next to last paragraph explains what will happen when the user inputs invalid data based on the column's data type. The DataError event will be thrown where you can display the error of your choosing.
This event will only be thrown after the text has been entered and the cell loses focus. If you want to limit characters as the user is typing, you'll have to manually check each character on a key event. I'll be discussing it further in an upcoming tutorial.
this code is running successfully. But it is not deleting the record or any message.
the code writer used only the Select query, you can edit the code by using Delete whith the WHERE condition..
use key press event on grid control write the code in key press event like,
if(e.keychar\<0 || e.keychar>9) e.Handle=false; else e.Handle=True;
check this link
http://www.mindstick.com/Articles/60574323-7e6c-424e-9265-93f7d534a64c/
Very helpful info.....Thanks...
Great article; simple to understand and precise. Many thanks.
Thanks, this was the first article I found on a professional (i.e. non-designer) way to bind the DataGridView.
man thanks a lot ! i was getting bugged by this problem ! i scanned msdn , this and that forum . documentation sucks till i landed up here ! wow man u did an excellent job . thanks a lot again
Nice article. Very straight forward. I too have been looking for this answer for awhile, mostly using Google.
I had to look for this in thousands of pages and here in few lines u show us how to do it nice and simple.
Kudos to u.
This article is just what I was looking for. Thanks for writing it!
WOW. . . . .
Very good information supplied in an easy read and easy understood way, nice work. Thank you for your effort.
really nice... thanks friend
Fantastic. The grid works great with the update() in the validating event. But, I'm having trouble figuring out when validating fires? I seem to be able to enter many rows before validating fires.
Curious, I use almost this exact same method for simple grids, but I don't use a bindingSource. I just call the update method of the dataAdapter. What does the bindingSource give you?
If you use the binding source you can handle its positionchanged event. It's the best place to trigger the update .
Thank you.
Been looking for a clean explanation of how all these different objects fit together for a long time. Thanks!!
Worked the first time.
Remember, if you have a placed a DataGridView in the form designer you don't need to this line that creates a new one.
DataGridView dgView = new DataGridView();
Replace 'dgView' with the variable you created.
Thanks for the site.
yes - thank you for that.
Hello Sir
thanks.
Gracias, muy util esta información... y muy bien explicado.
Thank You!
Supperayittundu nayinte mone!
edoooo!!!
So, How to update / insert data?
thanks
To update and insert data, all you have to do is modify the DataGridView. Adding rows to the DataGridView will add rows to the database when the OleDbDataAdapter is updated. Any cells modified in the DataGridView will also be updated in the database. You just have to remember to call dAdapter.Update(dTable) to update the database with the changes made to the DataGridView.
Update works when cell value is entered using keyboard but fails when cell value added via program code as shown below
datagridView1["Name", (dataGridView1.RowCount - 1)].Value = Clipboard.GetText();
how to resolve this?
Thank you for posting this great article, really helps.
Thanks for been so concise. I spent a lot of time reviewing internet articles and all of them are so bulky. This one is so small and quick to understand
;)
I also appreciate this article very much, but I have a related question: I created a datatable and bindingsource and bound the table to a listbox via the bindingsource at run time. I also specified the DisplayMember (a string) and ValueMember (that one is the record id) properties of the listbox, but I cannot get the record id from the SelectedValue property of the listbox. What I get is a DataSourceView (or stg.like that) that can't be cast to an int. Any opinions?
When i put the da.update(dTable) in the click event for a button i get a error saying that "da is not recognized".
How to solve this?
I'm in the same boat.
If you put all the load/binding code in the Form_Load event, and you put the code "dAdapter.Update(dTable)" in a button_click event then the data adapter (dAdapter) and data table (dTable) are out of scope.
And if you put that code in the Form_Load event, then it just updates your freshly fetched data - giving no time for the user to make any changes.
I love simplicity of this article, but it "simply" doesn't work. I know I am missing something totally basic, but I don't know what it is.
I did like you wrote, but I still can't update database. I tried to delete row from datagridview and to update row, but changes only performed to data table not to database.
Changes won't automatically be saved back to the database. You have to call Update on your OleDbDataAdapter. If you're already doing that then there's another problem I sometimes experience that you might be seeing also.
I'm sure yet what causes it, but sometimes the modified flag on a DataRow doesn't get set to true, even though a value has changed. What I've found is that if you suspend the bindings (bSource.SuspendBindings()), the modified flag will be set and the database will update correctly. Make sure you resume the bindings when you're done.
i am using this piece of code for update the way u r doing to fill a datatable but the grid is updating only not the db ..plz help..... which query i have to use for update..??
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\153.57.224.22\\cmt\\CMT.mdb"; OleDbDataAdapter dAdapter = new OleDbDataAdapter("",connString); DataTable dTable = new DataTable(); BindingSource bSource = new BindingSource(); bSource.SuspendBinding(); dAdapter.Update(dTable); dTable.AcceptChanges();
The query passed into the OleDbDataAdapter doesn't change from whatever you used to initially request the data. It looks like you forgot to create the OleDbCommandBuilder for your OleDbDataAdapter. This is the object that automatically generates update commands based on the changes that have occurred.
Thank you.
thanks for this great article!!!
Very helpful. Thank you!
very useful information. Thanks
PLZ i want to do the opposite : i want to update datagridview from database in real time plz help!!!!!!!!
NoussaL@live.fr
Simple and clear.. Nice
how do i convert the the result into an array?
example:
i have a COLUMN of words and i want it to convert to an array because i will use it in the string compartion..
When I do 'dAdapter.Update(dTable);' I get 'Syntax error in INSERT INTO statement'. Any help will be appreciated. Regards, Manne
try: cBuilder.QuotePrefix = "["; cBuilder.QuoteSuffix= "]";
Got this from http://www.pcreview.co.uk/forums/thread-1209233.php
useful tutorial, thanks a lot
This article is nice....Thanks for this.
Can any body provide some information how can I bind add custom coloums to datagrid like I can add in wen appication...
Developer4you.com
i'm trying to do the exact same thing using the MySQL data connector but for some reason i can compile with no errors, but my DataGridView shows nothing!
ok, figured it out. i didn't need the line 'DataGridView dgView = new DataGridView();' because i already had the DataGridView created in Design View. thanks for writing this up, it was very helpful!!
Don't forget bSource.EndEdit();
before dAdapter.Update(dTable);
or your last modifications will be lost.
I didn't use endedit method but update was working fine and also i left the gridview with the active row being the row where i made my last modification. How come this was working? Can anyone help. Also one more thing, if we use datatable instead of the binding source as the data source for the gridview then how to use endedit as datatable doesn't support such method.
It's just a great article, I am a professional programmer but I didn't see something like that kind of approach, It looks that you are also a professional coder. I also use to bind it like this. I really like your code. Keep it up GOD Bless you.
I tried this code, but when i call: dataAdapter.update(dataTable); an exception "Update requires a valid UpdateCommand when passed DataRow collection with modified rows". And i do not know how to solve it Your answer is welocme.
I sounds like you might not have an OleDbCommandBuilder associated with the OleDbDataAdapter.
Very interesting to read..I appreciate your knowledge and effort. Taake care,
this is what i am looking for.
REALLY GREAT !!!
For anybody who is using MySQL like me:
After added DataAdapter and CommandBuilder add the following lines:
as you can read on: http://forums.mysql.com/read.php?38,56936,60594#msg-60594
Cheers, Marco D.
i tried it on access database
but it doesn't delete record from databse
i try the code i get the error
“Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.”
any help is welcome
It sounds like it doesn’t know how to track changes made to the DataGridView. Does your database table have a primary key?
Change the query you are using to populate the datatable to include the primary key in your table.
I've set a primary key and can successfully change data to fields with a 'number' data type.
However, when I change the data in the fields with 'text' data type, the error 'Syntax error in UPDATE statement' comes up when the 'dAdapter.Update(dTable)' is executed.
Is there a way to check what query syntax was used by OleDbDataAdapter ?
Thanks in anticipation of your reply.
Hello...
I dont want the primary key column to be visible in my datagrid. is there any other way to exclude from the query. thanks for your effort
a good job! thanks for your artical.
I have been banging my head against the wall for days trying to figure out how to do this. I can't believe how poorly documented it is.
Your concise description is perfect.
When i am trying to use DataGridView control it is not showing the data.Data is comming to the DataSet and i have assigned DataSource if the DataGridView control is DataSet.But it is not displaying Data.I have tried with BindingDataSource also still same problem.Please help me in this regard
bSource.DataSource = dTable; dgView.DataSource = bSource;
Make sure you have both those rows included. I just had the same error until i noticed i forgot to add one row :)
See FishJD's comment from above.
Hi
I have followed your example without a hitch, however,when doing the update in the gridviews validating event
private void dataGridView1_Validating(object sender, CancelEventArgs e) { bSource.EndEdit();
dAdapter.Update(dTable); }
The following errors are encountered:
Error 1: The name 'bSource' does not exist in the current context
Error 2: The name 'dAdapter' does not exist in the current context
Error 3:The name 'dTable' does not exist in the current context
I know there is something simple to fix here, just don't know what it is.
The article is extremely helpful, thanks
Where did you declare bSource, dAdapter, and dTable? You'll probably have to make these member variables of the class in order to use them in other functions.
I placed the code in the click event of a button, as is, how would you declare the bSource, dAdapter, and dTable somewhere else, as the objects are instantiated with parameters ie
OleDbDataAdapter dAdapter = new OleDbDataAdapter(strSql, con);
AND
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
If i can get my head around this it will go along way to helping with other apps that i am coding
Much appreciated
Chris
PS I am coming from a VB6 background and finding the transition to C# a bit challenging
CODE:
private void btnSearch_Click_1(object sender, EventArgs e) { txtSearch.BackColor = Color.White;
if (txtSearch.Text.Trim() != "") {
try { OleDbConnection con = new OleDbConnection(clsConnSrt.GetConnectionString("PastelCostingSlip.Properties.Settings.PastelCostingSlipConnectionString").ToString());
string strSql; strSql = "SELECT * FROM Sheet1 WHERE PlantDescription LIKE '" + txtSearch.Text.Trim() + "%" + "'";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(strSql, con);
//create a command builder OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results DataTable dTable = new DataTable();
con.Open(); //fill the DataTable dAdapter.Fill(dTable);
//BindingSource to sync DataTable and DataGridView BindingSource bSource = new BindingSource();
//set the BindingSource DataSource bSource.DataSource = dTable;
//set the DataGridView DataSource dataGridView1.DataSource = bSource;
con.Close(); con.Dispose();
} catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } finally {
}
What's happening is you're declaring the variables inside the search event handler, which means they won't be available anywhere else except inside that function. All you need to is move the declaration to the class. Here's an example.
Here the DataTable is declared as a private member of the class, then set in the search event handler. Now any function inside MyClass can reference the dTable variable. Of course, you'll have to do this for all the variables you'd want to reuse, not just dTable.
hi... its best ... it solved my problem at once.... i was tring hard to insert the records that are searched through query...bt now finally its resolved by your guaidance and a little modification of mine can any one plz help me ... i want to make my some columns of data grid read only and just one write only... and then saving all the data back into the access table making sure that no value is missing....
'bSource' should be the current instants of oledb Adapteroes , hence it's not exist in the current context
Hi, thanks for the tutorial.
I can't get it to work. It doesn't display anything. I copy everything correctly but when I run the app it doesn't display anything. What could be the problem?
Hi
This is by far the best Tutorial I've read on DataGridView but one thing is maybe missing. Using the code above the DataGrid does not appear - I had to create a DataGrid by dragging the control onto my Form. Any ideas why the grid did not display please.
Thanks David
This tutorial assumes a DataGridView already exists. It does not cover how to create and place one on a control.
Hi
I don't think tutorials should assume anything - if the tutorial assumes you know something, then why would you even write tutorial at all. No one can assume anything if its aimed at many different programmers at different levels of knowledge.
But great tutorial all the same.
cheers David
David, that isn't quite true, if you assume nothing then you have to start from the ground up everytime you create any tutorial. You have to assume some knowledge or you don't have real starting point for the post.
I would love every tutorial to cover everything from the ground up but that isn't practically possible and we have plenty of other tutorials on the basics of most topics (not all).
Incorrect syntax near the keyword 'where'.
Hey if u r visiting this page....then its not expected to teach u all d things. For ur requirement author should also write how to initialize a new object. Why is he putting private keyword and all crap.....
So please don't comment the way you have done.
By the way great job done by Author.
Very great Article.. very simple to understand... Thanks thanks and thanks to you for this article
Very good article... Can I ask, if you have a DataGridView and add a new record through the bindingsource how do you get the primary key back to display in the grid. The primary key is an autonumber?
The primary key can be an autonumber - it depends on your specific database schema. In most cases, however, it is. Unfortunately, as far as I know, it's not extremely easy to get the new id back. You have to either re-fill the DataTable
and rebind it, or request the id of the new entry and manually update the binding source. It seams like there should be an easier way, I just don't know what it is.
sir,if i am inserting data into datagridview and after i dont want to save that.then what can i do.
Hello,
I really do like your article, but I have a question. What would be the best way to customize your columns. For example, when I bind a DataGridView to a DataTable the column headers are the field names in the database that filled the DataTable. How would I change the column header name in the DataGridView?
Use Aliases, problem solved
I am very grateful to you guys for your efforts thanx this has been solved my problem
I created a dataGridView and named it dgView but the grid doesn't show anything(gray square)
Got error on the following two lines:
Could you, please, help me to solve this: dAdapter.Update(dTable);
when my dTable depends on user choice. I have one Dataset with several tables, and name of the chosen Tableapears in Label1.Text.
How to save changes from dataGridView to Database?
Hello there. Im writing an application for an RFID reader to read RFID tags and save their IDs in a database. The program will read the IDs automatically and display it in a datagridview. My problem is my datadapter.update method doesnt work, resulting in my database doesnt get updated. I understand that the method needs an event from the datagridview to be fired before it can be called. From my program, I dont think any event from the datagridview is fired when IDs are read from the reader and displayed on the datagridview since all are automatic (I maybe wrong here). Are there any workarounds to use the datadapter.update method without any previous firing event from the datagridview?
Thanks...
I think you have to EndEdit() on the binding source before you update so that any changes are stored.
hey, thanx for the advice. i'll try it out...
t u.. :/
I have tried out the above code. It does display the data from database to datagridview. But it didn't update the changes made in datagrdiview to database.
So, I made a Primary key in my database and my database was successfully updated via datgridview.
My question is:
Is it possible to update database via datagridview without using Primary key?
We can updata database using dataGrid by using Unique Key, instead of Primary key by using SP
Hi,
Thank you for this great tutorial. I use .net programming occasionally. I had never understood the purpose of adapter, command and table objects. But you have stated it very clearly with example.
My concern is why do we have to associate command object to the adapter. Shouldn't this be implicitly done by the adapter? As you know... adapter is bridging database and our data table or a data source.
Thank you and regards,
Rashid.
Hi, Thanks for the great article. My question: What is MyTable? Where and how should I declare it? Thank you. Regards Bernkopf
hello...i have a problem ..while connecting datagridview with the database...during connection...when i click on new connection ....no new window is opened....plzzz help...
this code is running successfully. But it is not deleting the record or any message.
hello i have a function that return a dataset :
public DataSet dataSetReq(string myQuery,string myTab) {
myCommand = new OleDbCommand(myQuery, myConnection); //ExecuteSEL(myQuery) dAdapter = new OleDbDataAdapter(myCommand); OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter); mydSet = new DataSet(myTab); dReader = myCommand.ExecuteReader(); dReader.Close(); dAdapter.Fill(mydSet,myTab); return mydSet; }
and i have a piece of code in the onclick event of my botton : BindingSource bSource = new BindingSource(); bSource.DataSource = DecGlob.GstBD.dataSetReq(DecGlob.Req, "Fournisseur").Tables[0]; this.dataGridViewFour.DataSource = bSource; DecGlob.GstBD.dAdapter.Update(DecGlob.GstBD.dataSetReq(DecGlob.Req, "Fournisseur"), "Fournisseur"); the update deosn't work please help me !!!
I'm very happy and grateful for this method that programmatically binds a datagridview to a data source. Can anyone tell me what I'd have to do (in terms of the original tutorial) to replace one of the columns, which presently defaults to a DataGridViewTextBoxColumn, with the same data but as a DataGridViewComboBoxColumn? The combobox will be a small fixed set of text values. I am using an Access 2000 database, and my query is "SELECT * FROM Products". The Access text field is named "UnitsType". Two of the valid values for UnitsType are "drop" and "vcap".
Hi everyone! I want to save in database from a GridView in C# on WindowForm. Any Help please?
Here is working class with fewer modifications..
public partial class Form1 : Form { private OleDbDataAdapter dAdapter; private DataTable dTable;
public Form1() { InitializeComponent(); }
private void Form1_Load(object sender, EventArgs e) { OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Employee.mdb"); conn.Open(); String query = "SELECT * FROM tblEmployee";
//create an OleDbDataAdapter to execute the query dAdapter = new OleDbDataAdapter(query, conn);
//create a command builder OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results dTable = new DataTable();
//fill the DataTable dAdapter.Fill(dTable); //the DataGridView //DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView BindingSource bSource = new BindingSource();
//set the BindingSource DataSource bSource.DataSource = dTable;
//set the DataGridView DataSource dataGridView1.DataSource = bSource;
dAdapter.Update(dTable); } // Update button private void button1_Click(object sender, EventArgs e) {
dAdapter.Update(dTable); }
}
note: i have used visual Data Grid view so lines related to dataGridView are commented
wow its really helpful.thannnnnks. but does it work for other kinds of controls too.f.exa textbox. mikeehips@gmail.com tnx
just learning c#
Have the update on a button_click as below but keep getting this error message
System.Data.OleDb.OleDbException was unhandled Message=Syntax error (missing operator) in query expression '((EID = ?) AND ((? = 1 AND Tag IS NULL) OR (Tag = ?)) AND ((? = 1 AND BID IS NULL) OR (BID = ?)) AND ((? = 1 AND Sex IS NULL) OR (Sex = ?)) AND ((? = 1 AND Size IS NULL) OR (Size = ?)) AND ((? = 1 AND Grp IS NULL) OR (Grp = ?)) AND ((? = 1 AND FeedQty IS '.
Regards Dave
Ok I would hate to say how long I've spent on this but I just deleted the 3 date/time columns(that were empty) and it now works. Have added them back in and it appears to be working, but I won't hold my breath.
Dave
many thanks to the author. Great article.
I used it for a single user and it works great.
Can i also use this solution for a database which is used concurrently. I need the functionality that two users can access the db at the same time. How can i update the database and the other users view so that data keeps consistent?
Thanks for a feedback in advance
How can I add logic to modify the contents of a cell as the "fill" is occurring? I can't change my query to accomplish this. Shouldn't there be some event I can put some code in? (I've converted my database from Access to Foxpro. Access stores all text fields trimmed, but Foxpro has fixed length fields. I want to trim the blanks off of the text fields so that when the user edits the datagridview, they won't find all those trailing blanks out there.) I've searched for one, but can't find one I can make sense of.
Check out the CellFormatting event. It looks like it will be fired whenever the cell needs painted, so you can completely control how the value looks when it gets displayed.
Works great! Thanks! But had a wrinkle, solved in a couple ways. When this executes against columns that have a date, the Foxpro date gets converted to a C# 'datetime' with the result that it shows a '12:00 am' (or the like) as part of the date. So I must exclude my date fields. 1st way was this:
Then after much further research, I found I could detect the data type and make the IF simpler:
Seems to do the job fine, although I'm still not sure why my VFP date-only field got converted to a date-time. Intuitively I suspect it has something to do with c# having all dates as date-times, but then I wonder why the times didn't show up before I added a CellFormatting event.
Another quirk I discovered is when my grid allows new records to be added. In that case, my CellFormatting event code (the e.value=) has to be preceded by
or when the blank row paints, it bombs with a "Object reference not set to an instance of an object" message.
I figured there would be some quirks and corner cases. I'm glad you got it figured out!
Is it possible to bind, and change in database through a datagridview, joined tables? For example, table A has a foreign key to ID column of table B. But, while showing table A in DataGridView, I want to show B.Name, associated with that ID instead just that number which is useless to the user. That column would be read only, but I want to be able to change the rest of the DataGridView and update the changes to the database. Is it possible to do with adapters, command builder etc..?
Have you tried adding the JOIN to the statement passed into the OleDbDataAdapter? I wouldn't be surprised if everything "just worked".
It didn't, hence the question :) "Dynamic SQL generation is not supported against multiple base tables." The thing is, I don't even want to change the other table, just display the name column, so I don't need him to generate sql for multiple tables, just to refresh name column ih one changes foreign key.. Is it possible to use several adapters, one for each table? DataSource property takes only one source, but maybe it is possible to combine several datagridviews, or something..? Any suggestion on what to try is welcome.. I already tried to create two datagridviews, each with its source and adapter, and then combining its columns, but it is not allowed, at least not the way I tried it.. :\ (edit: sorry for not hitting reply)
Very nice article... But could not run it. Got two type of errors. If i edit an existing row i get : "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information." error message. If i attemting to add a row into the datagridview i get : "Syntaxfehler the INSERT INTO-Command" What im doing wrong?
Does the Ruckstande table have a column configured as the primary key?
Thanx for the advise... Now it has! But the Syntax-Error in the UPDATE and INSERT-Statement still appears.
Problem solved by allowing null values to the collumns and changing all collumn datatypes to string. I have also deleted all rows with null value cells from the database. It Works great now. As i know the causes of the previous problems, it should not be a great deal to handle with null and/or other type of values. Thank you very very much for the Tutorial!
is it for binding of data from datagridview 2 database?
Hi,
I think the article is great but I have one small problem. I'm not actually using a datagrid but have created an adapter, a datatable and a commandbuilder as described in the article but intend to modify the data manually in code as follows (btw - I'm using MS Access DB):
Although the data appears to have changed at runtime, the actual database has not changed.
I read a comment earlier regarding primary keys but wasn't quite sure if this affects me. I can't make changes to the schema of the database anyway as my application is intended only to access it in it's current form.
Any help would be much appreciated!
Just a quick update on my post. I tried the same method on the Northwind database to exclude my database as the point of failure but the problem still occurs. There must be something extra that I need to do.
Any help would be fantastic!
Could anyone help me for checking this code? It doesn't work. I try to find the way to change the forecolor for some field, but it's still change for all columns.
Any help will be appriciate.
You are updating the color for the column, not an individual cell. There are multiple ways to refer to a cell, but here is an example that would go through the rows, and then the cells. This makes the assumption you have populated the DataGridView already. So you would populate it, then run this code. Also make sure you have the 'Color' reference in System.Drawing.
This is exactly what I was looking for. Thank you for making it so easy to understand!
while updating the DataAdapter, it throw an exception telling: "Update require a valid UpdateCommand when passed DataRow collection with modifiec rows." it seems it's very simple but I cant find any solution for thins.
hi... how to add paging in datagridview using c#....
Why if I call the adapter.update(dt); do I get a invalid operation error
In windows Application I have 4 columns in datagridview ie, 1.Student Name. 2.Present 3.Absent 4.Leave. For student name i have created just column,for present, absent and leave i used checkbox where they can click if present or absent or leave.. Student name i have to bind from backend, Am not getting how to bind only one column of table from backend to only column of datagridview.. please help me.. if possible please mail me.. shrusharan@gmail.com,.. thanks in advance
Eddy can't dance!
Hey me!
Good article. Saved me a lot of time..
thx..one of the best code
nice..hey tell me that is this a only way in c# to connect with the databases?
It's nice and very helpful.. but it's not working when I include a row selection condition in the query.. like,, "select * from employee where dept=Sells".. .. when the attribute type is int or float it works fine.. like.. "select * from employee where salary=10000"..(works fine) but the problem becomes when attribute value be varchar.. like 'name' or 'dept' etc. Help me plz... Thanks in advance..
Add quotes around the string values: "select * from employee where dept='Sells'"
I am devleoping a C# based windows application. I am using Datagridview which retrieves data from table. It has columns like "Item ID","Item Name" and "Unit Price". When the user changes the Unitprice and ItemName, that has to be updated in the table. The table has two primary keys on two columns ItemGroupID, ItemID.
The Table design is as follows: ItemGroupID-->Primary Key Column ItemID-->Primary Key column ItemName Weight UnitPrice
This is my code for the save button
Please help me how to update the values in database. I am not using any binding control in the form. I am manually binding the data to the datagridview using dataset.
Thank you.
With Regards, ArunV
how to do this using sql server 2000 database. when i convert the given code to sql its not working. is there any changes to be made.pls answer this
OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand, connection);
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
// Create the Insert, Update and Delete commands. adapter.InsertCommand = new OleDbCommand( "INSERT INTO Customers (CustomerID, CompanyName) " + "VALUES (?, ?)");
adapter.UpdateCommand = new OleDbCommand( "UPDATE Customers SET CustomerID = ?, CompanyName = ? " + "WHERE CustomerID = ?");
adapter.DeleteCommand = new OleDbCommand( "DELETE FROM Customers WHERE CustomerID = ?");
// Create the parameters. adapter.InsertCommand.Parameters.Add("@CustomerID", OleDbType.Char, 5, "CustomerID"); adapter.InsertCommand.Parameters.Add("@CompanyName", OleDbType.VarChar, 40, "CompanyName");
adapter.UpdateCommand.Parameters.Add("@CustomerID", OleDbType.Char, 5, "CustomerID"); adapter.UpdateCommand.Parameters.Add("@CompanyName", OleDbType.VarChar, 40, "CompanyName"); adapter.UpdateCommand.Parameters.Add("@oldCustomerID", OleDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;
adapter.DeleteCommand.Parameters.Add("@CustomerID", OleDbType.Char, 5, "CustomerID").SourceVersion = DataRowVersion.Original;
I am getting this error msg while updating as well as Deleting the data.
"Object reference not set to an instance of an object"
Please help...! Thanks in advance....
Thanks for the awesome tutorial!!
Nice tutorial but I would be happy if anyone explain how to manuplate columns and rows in datagridview as I am new to c#
Excellent!!! ;-)
Very cool article, it helped me a lot. Thanks
This is nice article. It's help me lot thanks for sharing with us. Here is also a nice article which helped me to complete my task. Check this Url... http://www.mindstick.com/Articles/30148105-6777-467a-9ecc-82a2118387d0/?Insert%20Update%20Delete%20Records%20in%20CSharp%20.NET
It might be useful for you.
Im back to programming now since left them out about 5 months ago. Well, Good tutorial, clear explanation.. Thanks...
Is there a way to have the Datatable automatically pick up any changes that happen to the data on the DB? Or are they static until refreshed?
megastiv@stiv.com
Hi Thank You
Hi, I get error when I add these two lines.
//the DataGridView DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView BindingSource bSource = new BindingSource();
There is gridview not datagridview. Iam doing this on VS2010.
Error "Name or Typespace name missing" need to add reference.
Do I need to add any reference.
Thanks
Both types are in the System.Windows.Forms namespace. If you created a Windows Forms applications, you should already have the reference. If you're creating a WPF application, then you should use the WPF DataGrid. This tutorial does not apply to WPF applications.
i want to apply query on datagrid view acc to user need.. for eg: user enter name in textbox and corresponding to dis textbox value related rows are selected and data is fetch in grid view.. pls help. its urgent..
Thanks. Give me a best solution for my problem.
My problem is how to keep the datagridview updated when the underlying database is changed by another user
i want to apply query on datagrid view acc to user need.. for eg: user enter name in textbox and corresponding to dis textbox value related rows are selected and data is fetch in grid view.. pls help. its urgent..
do there any directives needed to include the report in the window service....im using visual studio 2010... gettin an error like"Error 1 The dataset ‘DataSet’ refers to the data source “”, which does not exist"
A good tutorial on Datagridview
http://csharp.net-informations.com/datagridview/csharp-datagridview-tutorial.htm
yang.
Hey Guys, I tried a lot but each time when I am executing my da.Update(ds) I am getting error "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
Here is my code
Please let me know/mail me if I am doing something wrong
I think your database table, Tbl_EmpDetail, just needs a primary key set. You have to do this through your database administration tools.
If this is a MS SQL database the primary key is set using the identity property.
Hello Mr.The Fattest Pls help me... i want to apply query on datagrid view acc to user need.. for eg: user enter name in textbox and corresponding to dis textbox value related rows are selected and data is fetch in grid view.. pls help. its urgent..
can any one let me know
how to update and delete records from ms access database in windows application in c sharp
Inserting,deleting,updating and editing records to a MS Access database using select checkbox
My WinForms application uses the below structure to populate a DataGridView. This all works well and follows the same structure described in this excellent tutorial. I have two design goals that I am struggling with however.
?1) I want to separate Form code from the Database code. (n-Tier concept). This is my primary question currently.
2)I want to make DataGridView and Database handling generic so it can be driven by meta-data, rather than hardcoding to specific tables or form views.
My current question is; what are best practices to persist the database objects (DataAdapter) so I can write back to the database without creating all of the structure over again for each write. Once the call to Getdata to create the dataset is complete, I suspect my data adaptor and command builder (which will get added once I figure out how to structure the code) get hauled off with garbage collection. I am guessing the answer will include creating an instance of some data object but would like to get some expert opinions on how to best handle this.
Class frmMain • Creates instances of DataGridView and BindingSource
Btn_Click events • Calls BuildDataGrid if DataGridView is empty • Moves current DataGridView to top of form
BuildDataGrid(DataGridView, bindingSource) • Gathers external meta-data, adds columns and sets properties to a DataGridView • Sets DataGridView.DataSource = bindingSource; • Calls GetData (sql string) which returns a dataset • Sets bindingSoruce.DataSource = ds; • Sets bindingSource.DataMember = "Table";
Class appData
Getdata(sql) • Creates OleDbConnection object • Creates OleDbDataAdapter • Creates DataSet • Opens dbConnection • Uses DataAdapter to populate dataset • Closes dbConnection • Returns DataSet
Thank you.
i cant see new record in datagridview.my code is: SqlConnection con = new SqlConnection("server=pc1\\sqlexpress;attachdbfilename=d:\\Data\\Data1\\data1\\yahya\\Projects\\database_employ\\database_employ\\employ.mdf;integrated security=true"); con.Open(); SqlCommand cm = new SqlCommand(); cm.Connection = con; cm.CommandText = "insert into tb1(id,fname,lname) values(@id,@fname,@lname)"; cm.Parameters.AddWithValue("@id", textBox1.Text); cm.Parameters.AddWithValue("@fname", textBox2.Text); cm.Parameters.AddWithValue("@lname", textBox3.Text); cm.ExecuteNonQuery(); tb1TableAdapter.Fill(employDataSet.tb1); dataGridView1.Invalidate(); dataGridView1.Refresh(); con.Close(); please help me
Hi guys It was so nice I have a problem I have 4 columns that one of them is for another table but I want to display it in grid view too I mean I have one column as id and another as name in another table how can I show both of them and update the table Any help would be appreciated
Thank you Sir .. Its a very nice and simple explanation.
Hi,
I have a problem. When I click my save button my access database does not update. What am I doing wrong?
[language] using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.OleDb;
namespace NVFinancialTracker { public partial class FormCategory : Form { string connectString; OleDbDataAdapter da; DataTable dt; BindingSource bs; OleDbCommandBuilder cBuilder;
public FormCategory() { InitializeComponent(); connectString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\NVMoneyTracker.accdb"; da = new OleDbDataAdapter("SELECT * FROM CATEGORY", connectString); cBuilder = new OleDbCommandBuilder(da); dt = new DataTable(); da.Fill(dt); bs = new BindingSource(); bs.DataSource = dt; dataGridView1.DataSource = bs; }
private void button1_Click(object sender, EventArgs e) { da.Update(dt); }
} } [/language]
Does anyone know how to create connectionstring for sdf database?
[c#] how can I select a row at DataGridView and connect this row at Table in Sql?plz help me ,very thank [/C#]
very nice post , thank you very much , i have an issue , the .update method works when the user enter the data manualy but it didn't when the data add programticaly , need hlep , sorry for the mistake spelling ,
Hi Wonderful Article. I am having some problem while using this code. here's my code."VS 2010"
string conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=(local);database=BookSelling;user=sa;password=**"; string query = "select *from book"; OleDbDataAdapter adp = new OleDbDataAdapter(query, conString); OleDbCommandBuilder cmd = new OleDbCommandBuilder(adp);
DataTable dtable = new DataTable(); adp.Fill(dtable); dataGridView1.DataSource = dtable;
it gives this error. "Can not start your Application. Workgroup file is missing".