Display More Added Columns by the user In Report viewer - c#

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();
}

Related

Multiple SQL Server statements do not work on same form

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?

Dynamic SQL issue - C# Forms (Datagridview)

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

DataSource for DataGridView is not showing the data of the table

Within Visual Studio 2017 I just created a DataGridView and linked a DataSource to it. It asked me for a connection string (which I gave). It showed the table from the database that I wanted in the DataGridView and it created automatically the correct columns within the DataGridView for me.
But for some reason when I start the application it does not show any data. I assume it connects to the database correctly otherwise it couldn't possibly know the name of my table and the columns within it. So how comes it sees my table but does not get the data?
So to test this I tried to make a simple RadDropDownList with help of the guide "LINK" But by following the steps for "Data binding at design time" I get the same exact result. It seems like it connects correctly but then it shows no data.
Does anyone knows why Visual Studio connects to my database with help of a DataSource but then does not gets any data from the table? Am I perhaps missing something?
Added:
I am using Microsoft SQL Server.
Yes, I have checked if the table contains data.
Try this:
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True"; // put your connection string
string sql = "SELECT * FROM Authors"; // change your table name
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Authors_table");
connection.Close();
dataGridView1.DataSource = ds; // put your gridview name
dataGridView1.DataMember = "Authors_table";

ASP.net weird grid view behavior

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.

Crystal Report Logon Failed Problem

I am using....
Framework 3.5 C# Visual Studio 2008 and web based application
I have created reports using Dataset i.e. my service gives me data set and I bind that dataset with report.
But sometimes CR viewer started popping up error "Logon Failed" with login box with dataset name filled in login information.
I am searching for its solution for quite some time but did not fine any suitable answer to this.
This error is unfortunately ambiguous because it is the generated error for dozens of unrelated problems. In this case, the "Logon failed" is likely due to an occasional schema mismatch.
The DataSet object can contain hierarchical data. If your service is returning a DataSet containing hierarchical data, and some of the children are missing, then its schema has effectively changed.
There are several ways to ensure that the DataSet has a matching schema. If you are serializing objects into XML and then generating the DataSet from that XML, then a simple way to achieve a consistent schema is to change your code from:
reportData.ReadXml(new MemoryStream(Encoding.UTF8.GetBytes(reportXml)));
to
reportData.ReadXmlSchema(schemaPath);
reportData.ReadXml(
new MemoryStream(Encoding.UTF8.GetBytes(reportXml)),
XmlReadMode.IgnoreSchema
);
where schemaPath points to an XSD file that was generated earlier in development with a call to
File.WriteAllText(
#"C:\MyTempPath\MyReportName.xsd",
reportData.GetXmlSchema(),
Encoding.Unicode
);
When generating the schema, you will also want that schema to be as complete of a representation of the data as possible, so you will want to use as complete of a hierarchy of data as possible. This is also the XML that the report must be created off of so that its schema matches. If the schema changes, then the report must be opened in the designer with the new data and you must "verify database" and then save the RPT file.
Are you passing along your creditials in your code:
ReportDocument rep = new ReportDocument();
rep.FileName = Server.MapPath("CrystalReport1.rpt");
set.SetDatabaseLogon("username", "password", "sql-server", "database"); // this line pass the login parameters required for login
After long efforts i figured the main reason, there was a mistake in my stored procedure which was returning data.
SP returns data from table1 or table2 (they both have same structure), but when I was picking data from table2 i did not write all the column names which were required.
Seems quite weird , i should get something like column not found error instead of database logon failed.
Try this out. Also make sure you have right version of crystal report in all places
private ConnectionInfo crConnectionInfo = new ConnectionInfo();
ReportDocument rpt = new ReportDocument();
protected void Page_Load(object sender, EventArgs e)
{
CrystalReportViewer1.Width = 900;
CrystalReportViewer1.ToolPanelView = ToolPanelViewType.None;
BindReport();
}
private void BindReport()
{
rpt.Load(Server.MapPath("ProductList.rpt"));
DataSet ds = getReportData();
rpt.SetDataSource(ds.Tables[0]);
CrystalReportViewer1.ReportSource = rpt;
}
private DataSet getReportData()
{
DataSet ds = new DataSet();
string ConnectionString = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "GetProductList";
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.Connection = con;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds, "ctable");
con.Close();
return ds;
}
I was facing the same issue at the time, when I moved the application from the development machine to the real server. It was an IIS7 MVC application( CR 13.0) with trusted authentication to the SQL server.
The way I fixed it, was by creating a new application pool for the application. I give permission for the new application pool user IIS APPPOOL\applicationpoolname to the SQL server database that was used in the application.
Then the error went away.
My assumption is that, the userlogininfo applied through code is not always used by the CR runtime , instead it uses the IIS user login info.

Categories