I am searching for a way to create dinamic Datasets to be binded to my reports
(I am using C# on Visual Studio 2015 Community).
Can anyone explain how can I do it?
The first idea is to create a Dataset from a query then bind it to my report,
but I cannot create a report without telling VS a DataSet (which must be connected to a DB using a static ConnectionString (VS purposes me only the Wizard, I have no idea on how to do it dinamically)
Example Code of what I would like to have:
DataSet myReportDS = ADO.getDS("SELECT * FROM" +
"Table1 JOIN Table2 ON Table1.pkey = Table2.fkey");
//here I am stuck because I don't know even how to add objects without a
//static connection to my report (Designer) and how to bind it.
Have also in mind that the DBMS is PostgreSQL.
Thanks a lot.
In the end I found this article to solve my problem
https://blogs.msdn.microsoft.com/magreer/2008/10/16/setting-the-datasource-for-a-report-at-runtime/
The problem in fact is that VS forces the user to have a static DataSet to permit the report creation. So basically I had to create a copy of my DB Schema in local environment, then I executed my queries normally and then used Report.Fill() method. As soon as the schema is the same it works!
You could use a SqlDataAdapter or OleDbDataAdapter.
For example:
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");
There are more examples on the msdn site.
Source: https://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.110).aspx
Related
I've been stumped on this problem for a while, and although I have searched up my problems online, I haven't had much luck. So in my Android program made in Xamarin, in the button click event, I try to send data to the server, however, I would get this error:
System.InvalidOperationException: Update requires the command clone to have a connection object. The Connection property of the command clone has not been initialized.
I am using this code at this point:
using (SqlConnection connection = new SqlConnection(cs))
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter($"Select * from Room", connection);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
Spinner roomsSPNR = FindViewById<Spinner>(Resource.Id.rooms);
int room = Convert.ToInt32(roomsSPNR.SelectedItem.ToString());
DataRow[] selected = rooms.Tables[0].Select($"RoomNo = {room}");
selected[0][3] = Id;
dataAdapter.Update(rooms); //Line giving the error
}
changeColors(Id);
I'm stumped on this, I can't really figure out why it is doing this. Can anyone help?
I have tried:
Setting the update.connection manually
Making an SQL command and putting the command builder's command into there(There is another error)
Setting the DataAdapter's update command to the method for the command builder
In the DataAdapter's initialization, I have changed the connection to the connection string
Many others that may not have any importance
Edit: Earlier in the code the program is able to read from the server and put it into 'rooms. On the other hand, I'm not familiar with making web services; is that what I need to do to allow it to update the database?
You cannot directly connect with a database in xamarin. You need to first create a webservice and use that web service to insert or fetch data from database.
If you need I will help you with webservices.
I am using VS 2012 express coding in C# and have an issue when adding data from a dataset (I use SQL Server CE) to a reportview. My code is this:
private void button1_Click(object sender, EventArgs e)
{
System.Data.SqlServerCe.SqlCeConnection con;
System.Data.SqlServerCe.SqlCeDataAdapter da;
DataSet ds1;
con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["MySalon.Properties.Settings.MySalonConnectionString"].ToString();
string sql = "SELECT * FROM CUSTOMER_PAYMENTS;";
try
{
con.Open();
da = new System.Data.SqlServerCe.SqlCeDataAdapter(sql, con)
ds1 = new DataSet();
da.Fill(ds1, "DayRep");
ReportDataSource datasource;
datasource = new ReportDataSource("DayRep", ds1.Tables[0]);
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(datasource);
con.Close();
reportViewer1.LocalReport.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I can see that datasource has the data but report when pressing the button remains blank (There is no error just blank).
Try to add the following line of code:
reportViewer1.LocalReport.ReportEmbeddedResource =
"Your_Name_Of_Project.Name_Of_Your_Report.rdlc";
It should be if you created your own .rdlc report file so to indicate to reportViewer where to take data from.
Also, where is this line of the code?
this.reportViewer1.RefreshReport();
Usually, it is added by the studio (if you code using it). It should be in the end of the code, just in the end of your try block. Anyway, it is "mustHave", without it your report really will remain blank.
Also, it seems to me that you should replace this line of code:
ds1 = new DataSet();
with this one:
ds1 = new DataSet("myDataSet"); //for exmaple, so to make dataSet have some name
and then rewrite this line of code:
datasource = new ReportDataSource("DayRep", ds1.Tables[0]);
with next:
dataSource = new ReportDataSource("myDataSet", ds1.Tables[0] as DataTable);
UPDATE
Well, you have no need to install rdlc teamplate to run and display reports via ReportViewer.
As is told here, (in examples), you may write it like this
// Set Processing Mode
reportViewer.ProcessingMode = ProcessingMode.Local;
// Set RDL file
using (FileStream stream = new FileStream("report1.rdlc", FileMode.Open))
{
reportViewer.LocalReport.LoadReportDefinition(stream);
}
So, the report will be loaded in the repoerViewer. The main problem here is that I have some .rdlc reports, so I can load them now. To create them without template you can use anther approach, so to create them programmatically - maybe this article can help you. Also, take a look here at MSDN.
UPD2
You can take a look at the text version of rdlc report by using this link. But remember that you won't be able to load exactly this rdlc into your reportViewer and see the data you want it to. That .rdlc is only an example, and every report should be created by the developer of the project. The main reason is that .rdlc I have uses DataSet you do not have cause it got data from dataBase you do not have. So, I think the only reason for you to look through this rdlc is only getting acquainted. To create .rdlc reports successfully, you should use approach I told about before. To get more information, you can try search in google "generate a report definition programmatically" or find some opportunity to create reports in IDE's just like Visual Studio.
Firstly, For Those who would like to ask WHY on earth am I DOWNSIZING from SQL SERVER to ACCESS, let me tell you the scenario.
There are some PC's with very low configuration, (256 MB RAM, 2GHzProcessor) I cannot install SQL Server. Hence I want major operations to carry out on SQL server and some data retrieving and auditing work to be done on Slower machine.
So here we go:
I want to copy table from SQL Server to MS Access 2007. I tried:
1)Connect to sql server, fill a datatable object by reading table from sql server.
2) Create a connection to MS Access, and use Dataadapter.Update method to update table to MS Access database.
However 2nd step is not working although its not throwing any error. Here is my code:
SqlConnection cnn = new SqlConnection(#"initial catalog=DBTempleERM;user id=aditya;password=Aditya_ravi$;Data Source=adityalappy\sqlexpress");
SqlCommand cmd = new SqlCommand("SELECT * FROM donationdetails", cnn);
cnn.Open();
System.Data.SqlClient.SqlDataAdapter sDA = new SqlDataAdapter(cmd);
DataTable donationdetails = new DataTable();
sDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;
sDA.Fill(donationdetails);
MessageBox.Show(donationdetails.Rows.Count.ToString());
OleDbConnection oleConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Jet OLEDB:Database Password=Aditya_ravi$;Data Source=C:\dbt.accdb");
oleConn.Open();
OleDbCommand oleComm = new OleDbCommand();
OleDbDataAdapter oDA = new OleDbDataAdapter(oleComm);
OleDbCommandBuilder oCb = new OleDbCommandBuilder(oDA);
oDA.Update(donationdetails);
No error is thrown at the end of the execution, but I cannot see any records copied from SQL Server to MS Access.
I learnt that SQL Bulk copy cannot be used to copy from SQL Server to Access.
I also want to add the primary key from SQL Server table to MS Access table.
Why dont you use SSIS to do this for you.
You can create a SSIS package to copy a sql table to MS access.
If you want to initiate by .NET then create a SSIS package and call it from .NET
For details
At this point, oDA is not connected to any table on the Access side:
oDA.Update(donationdetails);
So even though you have all the data in a DataTable, you haven't got a target to copy it into.
I don't think this is the best approach, but that's the core of why your code isn't working as it is.
Ancient question, but I'm betting the RowState of all your rows in donationdetails were Unchanged, so the DataAdapter treats them as "I don't need to do anything with this row."
You can use dataset object instead of datatable.
DataSet ds=new DataSet();
sDA.Fill(ds,tablename);
oDA.Update(ds);
I want to be able to edit a table in a SQL server database using c#.
Can someone please show me a very simple tutorial on connecting to the DB and editing data in a table.
Thank you so much.
First step is to create a connection. connection needs a connection string. you can create your connection strings with a SqlConnectionStringBuilder.
SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
connBuilder.InitialCatalog = "DatabaseName";
connBuilder.DataSource = "ServerName";
connBuilder.IntegratedSecurity = true;
Then use that connection string to create your connection like so:
SqlConnection conn = new SqlConnection(connBuilder.ToString());
//Use adapter to have all commands in one object and much more functionalities
SqlDataAdapter adapter = new SqlDataAdapter("Select ID, Name, Address from myTable", conn);
adapter.InsertCommand.CommandText = "Insert into myTable (ID, Name, Address) values(1,'TJ', 'Iran')";
adapter.DeleteCommand.CommandText = "Delete From myTable Where (ID = 1)";
adapter.UpdateCommand.CommandText = "Update myTable Set Name = 'Dr TJ' Where (ID = 1)";
//DataSets are like arrays of tables
//fill your data in one of its tables
DataSet ds = new DataSet();
adapter.Fill(ds, "myTable"); //executes Select command and fill the result into tbl variable
//use binding source to bind your controls to the dataset
BindingSource myTableBindingSource = new BindingSource();
myTableBindingSource.DataSource = ds;
Then, so simple you can use AddNew() method in the binding source to Add new record and then save it with update method of your adapter:
adapter.Update(ds, "myTable");
Use this command to delete a record:
myTableBindingSource.RemoveCurrent();
adapter.Update(ds, "myTable");
The best way is to add a DataSet from Project->Add New Item menu and follow the wizard...
Assuming you're using Visual Studio as your IDE you could just use LINQ to SQL. It's a pretty simple way to interact with your database and it should be pretty quick to get going.
Using LINQ to SQL is a pretty simple walk through in getting it up and running.
Have a read of the MSDN tutorial on Creating Data Applications. You may be able to clarify your question, or find the answers you need.
There is info on editing the data in the app but you have to get connected and load it into your app first.
The only reason to do this in C# is if you want to automate it somehow or create an interface for non-technical users to interact with the database. You can use a GridView control with an SQL datasource to manipulate the data.
#kevin: if he's just learning, I think its probably simpler to have him use SQLCommand object (or SQLDataAdapter).
How can I get a DataSet with all the data from a SQL Express server using C#?
Thanks
edit: To clarify, I do want all the data from every table. The reason for this, is that it is a relatively small database. Previously I'd been storing all three tables in an XML file using DataSet's abilities. However, I want to migrate it to a database.
You can use the GetSchema method to get all the tables in the database and then use a data adapter to fill a dataset. Something like this (I don't know if it compiles, I just paste some code and change it a bit):
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");
DataTable tables = null;
DataSet database = new DataSet();
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = "Data Source=(local);Initial Catalog=Northwind;Integrated Security=True";
string[] restrictions = new string[4];
// Catalog
restrictions[0] = "Northwind";
// Owner
restrictions[1] = "dbo";
// Table - We want all, so null
restrictions[2] = null;
// Table Type - Only tables and not views
restrictions[3] = "BASE TABLE";
connection.Open();
// Here is my list of tables
tables = connection.GetSchema("Tables", restrictions);
// fill the dataset with the table data
foreach (DataRow table in tables.Rows)
{
string tableName = table["TABLE_NAME"].ToString();
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand command = factory.CreateCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select * from [" + tableName + "]";
adapter.SelectCommand = command;
adapter.Fill(database, tableName);
}
}
EDIT:
Now I refactored it a bit and now it's working as it should. The use of DbConnection and DbProviderFactories is for database engine abstraction, I recommend using it so you can change the database engine changing this line and the connection string:
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OracleClient");
The GetSchema method will retrive all tables from your database to a DataTable and then we get all the data from each table to the DataSet using the DataAdapter.
I think you need to narrow down the question somewhat... All the data? You mean, all the data in every table in every database? Well, the only answer to that is, a lot of code.
To connect to and talk to a SQL Server Express database engine, use the classes in the System.Data.SqlClient namespace, namely:
SqlConnection: Connect to the database
SqlCommand: Talk to the database
SqlDataReader: Iterate over data retrieved from the database
You can check the MSDN pages for all of these classes by clicking on the links above.
Here are some overview-links with more information:
CodeProject: Beginners guide to accessing SQL Server through C#
DevHood: Accessing SQL Server Data in C# with ADO.NET
Note that by and large, you use a SQL Server Express database engine the same way as the full SQL Server product, the difference is more in the tools you get with it, and some limitations in the express engine. Other than that you can just use the classes and language that you would use for a normal SQL Server database engine installation.
If this post didn't answer your question, please elaborate, and you have a higher chance of getting the answer you seek.
This can be done by using dataAdapter class.