I am working on a C# project with a Microsoft SQL Server database.
This is how I have connected the database:
DataSet ds_display = new DataSet();
SqlDataAdapter da_display = new SqlDataAdapter("Select * from Files", "Data Source=DESKTOP-21EVLOU\\SQLEXPRESS;Initial Catalog=UPM;Integrated Security=True");
da_display.Fill(ds_display, "Files");
dataGridView1.DataSource = ds_display.Tables["Files"].DefaultView;
The code works fine for all operations including reading data, writing data, updating data and deleting data as well. However, it works only when each operation is on individual form, not on a single form.
I have created several different panels and show/hide them based on the respective button. Each panel has its own operation and Data Grid View. The display option works fine but the addition, updating and deleting operations do nothing.
Can you please help identify the issue here?
Related
I am currently trying to update my DataGridView to my database. I want to be able to update it with the enter key. But I am getting this error:
"Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information."
Here is a picture of the code(as well its below in code snippet)
Some of the code
Here is how the Datagridview is loaded:
private void RampBoardLoader()
{
SqlConnection connection = new SqlConnection(ConnectionLoader.ConnectionString("Threshold"));
connection.Open();
SqlCommand selectRampBoard = new SqlCommand("Select_Ramp_Data", connection);
selectRampBoard.CommandType = CommandType.StoredProcedure;
selectRampBoard.Parameters.AddWithValue("#DateID", dateTimeRamp.Value.Date);
dt = new DataTable();
dataAdapter = new SqlDataAdapter(selectRampBoard);
dset = new DataSet();
dataAdapter.Fill(dset, "Ramp_Board");
dgvRampBoard.DataSource = dset.Tables[0];
connection.Close();
}
Here is where I'm trying to update the datagridview:
private void dgvRampBoard_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
scb = new SqlCommandBuilder(dataAdapter);
dgvRampBoard.EndEdit();
this.dataAdapter.Update(dset, "Ramp_Board");
}
}
I've been looking around to try to find the answer to this. Every post I see everyone says that you need to make sure your table has a primary key. My table does have a primary key. It has 2 primary keys. "Flight Number" and "DateID". I'm not sure if it's because I have 2 primary keys, if that's why I'm getting this issue.
Attached is image of Database of my stored procedure. You can also see the columns, I have 2 primary keys
Stored Procedure
How to make life easy:
(Note; this only works in a net framework project; the designer has bugs in net core and Microsoft have disabled it. There are tricks you can pull if you want to work in core, but they basically entail using a net framework project to do the editing and a netcore to do the running)
add a dataset type file to your project
open it, right click its surface, choose add tableadapter
Set up your connection
Choose to use stored procedures to get your data
Choose your sprocs (I assume you have one for updating ?)
Name the Fill/GetData methods appropriately (FillByDateId ?)
Save the dataset
Go to a new form
Open DataSources window on View menu, other windows
Drag the node representing your table, onto your form. You should see a grid, binding source, dataset and navigator appear
That's it, you should be able to just run the app now, enter some date Id in the box, hit fill, change the data, hit save..
You can find the code the designer write for you in the normal code behind and in the FormXx.Designer.cs files if you're curious how it works. A tableadaptermanager will call tableadapter.Update(datatable) on "parent, child" order for every table that needs updating. Table adapter's Update uses the InsertCommand, UpdateCommand and DeleteCommand as appropriate to persist each row change according to what the row state is
I created a windows form application using c# and sql database.
At the run time, I was able to add/delete columns in the datagridveiw and get the data updated. This way, when I reopen the application the data are saved, I was able to get a report viewer that I designed statically with the wizard. However it only shows the columns that were added in the design phase not the run time.
How can I display the modifications that occur to the data (adding or deleting columns) at the run time in the report viewer?
Suppose I designed the report to have three columns Name, LastName, money, and get the report successfully at the runtime, and then I added some new columns say (Age,Country)
during the run time. When I try to get the report I only get 3 columns (Name, LastName, Money) with updated Rows But not added columns.
I just solved the same problem. I was searching for a few days in internet but I couldn't find a good answer for it. So I hope my post will help somebody to overcome the same problem.
All you need to do - just define manually the connection, refill the dataset and bind the source to reportviewer. Here is my project example:
using Microsoft.Reporting.WinForms;
private void ReportForm_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\GD Robotics\VisualProjects\GDPolin\GDPolin\PolinaDB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlDataAdapter reportDBTableAdapter = new SqlDataAdapter("SELECT * FROM [ReportDB]", conn);
DataTable polinaDBDataSet = new DataTable();
reportDBTableAdapter.Fill(polinaDBDataSet);
conn.Close();
this.reportViewer1.Reset();
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.ReportPath = #"D:\GD Robotics\VisualProjects\GDPolin\GDPolin\Report1.rdlc";
ReportDataSource rds = new ReportDataSource("DataSet1", polinaDBDataSet);//"DataSet1" is the name of your dataset. Go to .rdlc form>VIEW>Report Data>"Right click on dataset">Dataset Properties
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.RefreshReport();
}
As a quick background, I'm a beginner at database programming so forgive me if anything that I post here doesn't make sense or is outright dumb.
I'm trying to make a WinForm application that will allow users to connect to a .mdb Access 97 database of their choosing, allow the user to make changes (e.g. add new data rows on WinForm which will then be applied to the original .mdb database), and sync those changes across different .mdb Access 97 databases if desired.
To give you an idea of what I have so far. I have successfully connected to a .mdb Access 97 database using C# and I output the database table contents into a DataSet object from which I then dumped into a C1FlexGrid (code will follow momentarily). Now before anyone mentions anything, I cannot upgrade the database file to a newer version, so it has to stay as an Access 97 version file.
Here is the code I used to connect:
dbConnection = new OleDbConnection(#"Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path);
dbCommand = new OleDbCommand("SELECT * from MAIN", dbConnection);
dbDataAdapter = new OleDbDataAdapter(dbCommand);
dbDataSet = new DataSet("MasterLanguageDB");
dbConnection.Open();
dbConnectionIsOpen = true;
// connection is successful, unlock connected mode features
EnterDatabaseConnectedMode();
dbDataAdapter.Fill(dbDataSet);
flexGrid.DataSource = dbDataSet.Tables[0];
My question is this: is the C1FlexGrid that I now have populated with the .mdb database file contents "binded" to the .mdb file? Because 1, I didn't bind the datasource the way Microsoft suggests doing it by way of the Add Data Source wizard in Visual Studio 2008 (because the user can connect to any .mdb database they choose -- not just one) and 2, I want whatever changes I make to the C1FlexGrid to apply to the original database.
If the answer is no, how do I create that "binding" or add the rows to the database?
The ADO.NET classes like Dataset or DataTable are disconnected objects.
Meaning that they can't directly update the database.
The OleDbDataAdapter has a method called Update that takes care to send all the modified data to the database.
So, supposing you have a button somewhere to save your changes, then you need to call in the click event
dbDataAdapter.Update(dbDataSet);
However this requires that you keep the object instances at the class global level
Another point is the need to prepare the dbDataAdapter.InsertCommand, dbDataAdapter.UpdateCommand and dbDataAdapter.DeleteCommand.
These commands could be created simply using an instance of OleDbCommandBuilder just after you have set the SelectCommand
dbDataAdapter = new OleDbDataAdapter(dbCommand);
OleDbCommandBuilder cb = new OleDbCommandBuilder(dbDataAdapter);
I'm taking a class in C# web dev and I'm currently trying to display data from a .mdb (Microsoft Access) database. I have two pages that both want to show a table stored in the database in a grid view. One page's form uses function that connects the the db and then writes to the table to the grid. it connects with this call:
sqlConn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
sqlDA = new OleDbDataAdapter("select * from tblPersonnel where LastName = '"+strSearch+"'", sqlConn);
//Initialize a new activity
DS = new dsPersonnel();
//Add rows to the dataset from the data source
sqlDA.Fill(DS.tblPersonnel);
The database is called PayrollSystem_DB.mdb. In the other page I placed a SqlDataSource control on the page and connected it to PayrollSystem_DB.mdb. Then set this to the gridView. However when running, the the first page shows a long table with data I've entered since last week. and the 2nd page shows only data from the first day I tested it. Looking at the db in the vs explorer the tables are identical to teh second page.
So I'm wondering were all the other data is being stored that the first page is showing? Am I unknowingly using a database I can't see in the solution?
Just a guess, but have you tried clearing your browsers cache and then looking at the first page again? Try that. If the data is still showing I would compare the size of the MDB before and after an insert to see if the MDB grows. If not, try a search of all the files on your PC limiting it to only files modified recently, I think that will at least help you find where the data is being stored.
I am working in visual studio 2010 creating a ASP web application. I am trying to implement a search function with a grid view, where I will be passing in an ADO select command into a dataset and filling up the datagrid with my desired SQL. I know this is possible for winforms and datagridviews but for some reason, it is acting strangely on my ASP application. Here is some code...
protected void btn_search_Click(object sender, EventArgs e)
{
SqlConnection cs = new SqlConnection("Data Source=WILSON-PC; Initial Catalog=KamManOnline; Integrated Security=TRUE");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("SELECT * FROM vw_orderView WHERE Supplier = #Supplier", cs);
da.SelectCommand.Parameters.Add("#Supplier", SqlDbType.VarChar).Value = ddl_SupplierView.Text.ToString();
ds.Clear();
da.Fill(ds);
gv_search.DataSource = ds.Tables[0];
gv_search.DataBind();
}
What happens is it picks out the right amount of data but does not show it on the grid view. For example, say if I had 3 fields as Wilson for the supplier. When I click my search button, it would bring out 3 rows but they are empty. Any ideas or another way to walk around this? Thanks!
P.S. I tried using the databind wizard but eventrually I want more flexability in my search, for example
SELECT * FROM vw_orderView WHERE (Supplier = #Supplier OR #Supplier IS NULL).
I tried writing this in the query builder but I need to add some if condition to say whether supplier will have a value or be null (check box). If this is the right approach, then please say so. Thanks
I would do the following to troubleshoot.
Run the query directly from SSMS to verify that you get back the results you expect.
Make sure the GridView has AutoGenerateColumns=true if you are not manually defining Columns.
Run in debug mode with a breakpoint set on ds.Clear() and inspect the freshly added Parameter to see that it contains the value you expect.