(First of all I'm so sorry about my english, because I'm a stranger and I don't know well)
I'm working in a school project. But I need to set a DataTable as DataSource in ReportViewer. First the user type the ID of the Document, and click on the button, the button calls an class that do a select in my database and return 12 fields. I've created a DataSet with all fields that the select results and I've selected it as the Report DataSource. But I need to transfer the data of the select to the DataSet, because when I start my application the Report has an error. Here is the code, and I hope you can help me! Thanks.
Buttton Code:
SelectDocumento doc = new SelectDocumento();
doc.ImprimirDoc(int.Parse(txtID.Text));
Class that select data in my database:
public void ImprimirDoc(int id)
{
string pesquisar = "CALL SP_Imprimir_Documento(" + id + ")";
MySqlConnection con;
con = new MySqlConnection("Persist Security Info=false; server=localhost; database=hospital; uid=root; pwd=");
MySqlDataAdapter adapter = new MySqlDataAdapter(pesquisar, con);
DataTable dt = new DataTable();
dt.TableName = "DataSet1";
con.Open();
adapter.Fill(dt);
ImprimirDocumento imprimir = new ImprimirDocumento(dt);
imprimir.ShowDialog();
}
Code of the Report Form:
private DataTable proc;
public ImprimirDocumento(DataTable select)
{
InitializeComponent();
proc = select;
}
ConexaoHospital bd = new ConexaoHospital();
SelectDocumento doc = new SelectDocumento();
private void ImprimirDocumento_Load(object sender, EventArgs e)
{
this.rptDocumento.RefreshReport();
this.rptDocumento.LocalReport.DataSources.Clear();
Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource("DataSet1", proc);
this.rptDocumento.LocalReport.DataSources.Add(rprtDTSource);
this.rptDocumento.RefreshReport();
}
Error that the Report Displays:
Error
If someone have a simmilar problem this way of my post is correct and my problem was because my ReportViewer DataSet name was different than my DataTable. My DataTable name was "DataSet1" and my DataSet name was "Documento". I changed the DataSet name for "DataSet1" and it works.
Related
I have a dataset called "dts_Material_Report" which is used to generate reports.In that data set I have a tableAdapter called "dt_report_Received_Materials".
Previously I have load the data to that table adapter with following code ,
private void generate_report( string qry )
{
string query, qry1;
query = qry;
int pr_id = Form_Common_PCM.pr_id;
clz_Common_SqlConnection con = new clz_Common_SqlConnection();
SqlDataAdapter sda = new SqlDataAdapter(query, con.ActiveCon());
DataSet dts = new DataSet();
sda.Fill(dts, "dt_report_Received_Materials");
rdc.SetDataSource(dts);
crystalReportViewer1.ReportSource = rdc;
crystalReportViewer1.DisplayToolbar = true;
crystalReportViewer1.Show();
}
But currently I am having all the data which I need to generate the report in one of my data table called "dt_mat_cost".
int Ref_ID_s_category;
Ref_ID_s_category = Convert.ToInt16(cbo_sub_category .SelectedValue );
int pro_id = Form_Common_PCM.pr_id;
clz_Received_Material_Summary rms = new clz_Received_Material_Summary();
DataTable dt_mat_cost = rms.Summary_Material_Cost_Filter_By_Project_By_Sub_Category(Ref_ID_s_category);
Now i want to load those data from "dt_mat_cost" to my tableAdapter "dt_report_Received_Materials" .Is there any way to do this.
Thanks in Advance.
One way to resolve this would be to put the DataTable into a DataSet and then run the crystal code as shown below. You may be able to just set the ReportSource to the datatable but I do not recall off the top of my head if that will work.
DataTable dt_matCost = rms.Summary_Material_Cost_Filter_By_Project_By_Sub_Category(Ref_ID_s_category);
DataSet dts = new DataSet();
dts.Tables.Add(dt_matCost);
//ds.Tables[0].TableName = "Whatever CR thinks it is"; // may need to set for CR
rdc.SetDataSource(dts);
crystalReportViewer1.ReportSource = rdc;
crystalReportViewer1.DisplayToolbar = true;
crystalReportViewer1.Show();
How do I display a database table (my database is sdf) to the datagridview?
Here is my code:
private void Show_Button_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM Contact_List";
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Co-op\Contact\Contact\ContactDataBase.sdf;Password=********");
using (SqlCeDataAdapter adap = new SqlCeDataAdapter(query, con))
{
DataTable dat = new DataTable();
adap.Fill(dat);
dataGridView1.DataSource = dat;
}
}
The code above doesn't show any data to the datagridview. It only shows a new row with nothing in it. I am using Window Forms application.
This is the Error I get:
'System.Windows.Forms.DataGridView' does not contain a definition for
'DataBind' and no extension method 'DataBind' accepting a first
argument of type 'System.Windows.Forms.DataGridView' could be found
(are you missing a using directive or an assembly reference?)
One suggestion please try Visualize the DataTable in debug mode with breakpoints.
Make sure that data is available in DataTable
Try this sample code:
public void FillDataTable(string sSQL, DataTable dt)// DataTable operations
{
this.cmd = new SqlCommand(sSQL, this.conn);
this.dataAdapter = new SqlDataAdapter(this.cmd);
this.dataAdapter.Fill(dt);
}
Usage:
DataTable preview=new DataTable();
FillDataTable("SELECT * FROM Contact_List", preview);
dataGridView1.DataSource = preview;
Hopefully it must work .
in C# and windows Form,
I have a database like this:
and this is how I using a class put it's data into a datagridview:
class DBConnection
{
public static void GetList(Form2 frm2)
{
string DBPath = Application.StartupPath;
OleDbConnection Connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+DBPath+#"\DataBase\SampleFeeds.accdb");
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary", Connection);
DataTable Dtable = new DataTable();
DataA.Fill(Dtable);
frm2.SelectedFeeddataGridView.DataSource = Dtable;
}
}
and this is my form load:
private void Form2_Load(object sender, EventArgs e)
{
DBConnection.GetList(this);
}
So far everything is ok.
now I have a question:
for example I have a list box FeedSelectListBox,
I want to when user click on a button GrassLegumeForagebtn my FeedSelectListBox fill with only all of Feed Names that are in the category of Grass / Legume Forage.
how should I do that ?
with help of Damirchi My problem solved
//-----------------
But now I have another question:
I want to when user select a feed from list box all of it's data from data base (like name, number, feed type and ,,,) put in a data grid view.
I used this code on my SelectFeedbtn but it doesn't work :
private void SelectFeedbtn_Click(object sender, EventArgs e)
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
string FeedSelectedID = FeedSelectListBox.SelectedValue.ToString();
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID = 'FeedSelectedID'" , Connection);
DataTable DTable = new DataTable();
DataA.Fill(DTable);
SelectedFeeddataGridView.DataSource = DTable;
}
And ValueMember property of FeedSelectListBox is ID but the error is :
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll.
I even use this query but it still doesn't work:
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID =" FeedSelectListBox.SelectedValue , Connection);
at first you most set the DisplayMember and ValueMember properties of FeedSelectListBox and use this code on click event.
you can put this code on GrassLegumeForagebtn click event.
string DBPath = Application.StartupPath;
OleDbConnection Connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+DBPath+#"\DataBase\SampleFeeds.accdb");
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where category='Grass / Legume'", Connection);
DataTable Dtable = new DataTable();
DataA.Fill(Dtable);
frm2.FeedSelectListBox .DataSource = Dtable;
I've been working on this since yesterday and I just can't update my database.
There are 3 tables. Here is a piece of code of one of WinForms. It loads data and display but after changing sth manually in the grid I get either errors by calling Update or anything happens at all.
please help because I'm going crazy.
public partial class Form3 : Form
{
//instance fields
private export2Excel export2XLS;
private DataSet _dataSet;
private BindingSource _bsrc;
private OleDbDataAdapter _dAdapter;
private OleDbCommandBuilder _cBuilder;
private DataTable _dTable;
private void button1_Click(object sender, EventArgs e)
{
//create the connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source='C:\\Documents and Settings\\dorota\\Moje dokumenty\\Visual Studio
2010\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\artb.mdb'";
//create the database query
string query = "SELECT * FROM Samochody";
System.Data.DataSet DtSet = new System.Data.DataSet();
_dataSet = DtSet;
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
dAdapter.FillSchema(_dataSet, SchemaType.Source);
_dAdapter = dAdapter;
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(_dAdapter);
_cBuilder = cBuilder;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
_dTable = dTable;
//fill the DataTable
_dAdapter.Fill(_dTable);
//_dAdapter.TableMappings.Add("Samochody", "Table");
_dAdapter.Fill(_dataSet);
// --------------------- to datagridview !
//BindingSource to sync DataTable and DataGridView
BindingSource _bsrc = new BindingSource();
//set the BindingSource DataSource
//bSource.DataSource = _dTable;
_bsrc.DataSource = _dTable;
//_bsrc = bSource;
//set the DataGridView DataSource
dataGridView1.DataSource = _bsrc;
}
}
and here... :
private void sqlsave_Click(object sender, EventArgs e)
{
//int i=_dAdapter.Update(_dTable);
_dAdapter.Update(_dataSet.Tables["Samochody"]);
//_dAdapter.Update(_dataSet,"Samochody");
}
//---------------------------------------------------------------------------------
ok. I have changed sqlsave method for this
private void sqlsave_Click(object sender, EventArgs e)
{
try
{
//_dAdapter.Update(_dataSet.Tables["Samochody"]);
OleDbCommand oldb= _cBuilder.GetUpdateCommand();
int i=oldb.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show(i+" rows affected.");
//_dAdapter.Update(_dataSet,"Samochody");
}catch(OleDbException oldbex){
System.Windows.Forms.MessageBox.Show(oldbex.ToString());
}
and now I get finally sth more informative than "Error in"
An unhandled exception of type 'System.InvalidOperationException'
occurred in System.Data.dll Additional information: ExecuteNonQuery
requires an open and available Connection. The connection's current
state is closed.
so let me changed sth and I will let you know if this is it!
//--------------------------------
no. no. too fast, can't last. now while trying to save I've got exception again,
connectin is opened, but (I can't post the image) when I debug this I see that my object of OleDbCommand type as _commandText has
"UPDATE Samochody SET Item=?, Data dyspozycji autem od=?, ..."
and so on.
I think this is the reason. Am I right? What to do?
You didn't provide a connection for your OleDbDataAdapter. Try it something like this:
The example is different from your code but it shows the declaration of New Connection and passing it to the OleDbDataAdapter
string connetionString = null;
OleDbConnection connection ;
OleDbDataAdapter oledbAdapter ;
OleDbCommandBuilder oledbCmdBuilder ;
DataSet ds = new DataSet();
int i = 0;
string sql = null;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;";
connection = new OleDbConnection(connetionString);
sql = "select * from tblUsers";
try
{
connection.Open(); // your code must have like this
oledbAdapter = new OleDbDataAdapter(sql, connection);
oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ds.Tables[0].Rows[i].ItemArray[2] = "neweamil#email.com";
}
oledbAdapter.Update(ds.Tables[0]);
connection.Close();
MessageBox.Show ("Email address updates !");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I've found the answer:
But a better approach would be to use drag-and-drop and learn form the code.
Select Data|View Datasources. Your dataset should be visible in the DataSources Window.
Drag a table to a (new) form. VS2005 will add a load of components and a few lines of code.
The form will now have a instance of the dataset and that is your reference point for Adapter.Fill and .Update methods.
Easy and works great! : D
I've found it here: https://stackoverflow.com/a/548124/1141471
I had windows form and I added combobox which bin data from database I added my code but this error apeared (invalid column name Category) altought the name was right .
public Category()
{
InitializeComponent();
CategoryParent();
}
private void CategoryParent()
{
using (SqlConnection Con = GetConnection())
{
SqlDataAdapter da = new SqlDataAdapter("Select Category.Category,Category.Id from Category", Con);
DataTable dt = new DataTable();
da.Fill(dt);
CBParent.DataSource = dt;
CBParent.DisplayMember = "Category";
CBParent.ValueMember = "Id";
}
}
Change your query like this,
Select Category.Category as CatName ,Category.Id from Category
i-e use an alias like "CatName" for your column and set Display member like this,
CBParent.DisplayMember = "CatName";
Hope it shall help.
I checked the connection and I found the connectionstring was wrong