How do I sync data from a database to a combobox - c#

I'm creating a form of which I have to show the data from a database into a combo box and I need help to do it, please
I have already tried to download MySql Server, however, it only supports up to Visual Studio 2017 and I have Visual Studio 2019
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Code\C#\MyFirstUI\MyFirstUI\LOGIN.mdf;Integrated Security=True"))
{
try
{
string query = "select USERNAME from LOGIN";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Username");
comboBox3.DisplayMember = "Userame";
comboBox3.DataSource = ds.Tables["Username"];
}
catch (Exception ex)
{
// write exception info to log or anything else
MessageBox.Show(ex.Message,"Error occured!");
}
}
I would have expected the data from the database however, I got an output of nothing

Set comboBox3.ValueMember="USERNAME" and comboBox3.DisplayMember="USERNAME" , Use "USERNAME", not "Userame", because your sql is select USERNAME
Check if ds.Tables["Username"].Rows.Count>0

Related

C# sqlDataAdapter issue

all I try to load data from sql by following code using SQL server. I checked connection is normal and most sql are available to load. But in certain cases, I can't load data with following error:
"The conversion of the varchar value '2863289685' overflowed an int column.
The statement has been terminated."
and that sql is runnable in sql server management studio, but can't load by following code, please help me with possible solution, thanks!
try
{
SqlCommand command = new SqlCommand(sql, conn);
command.CommandTimeout = 0;
SqlDataAdapter sqlDa = new SqlDataAdapter(command);
DataSet ds = new DataSet();
sqlDa.Fill(ds);
Console.WriteLine(ds.Tables.Count);
dt = ds.Tables[0];
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}

Reportviewer with MySQL stored procedure. Report not showing data (winform)

I built a form that contains a report viewer and also created a stored procedure in MySQL workbench 8.0. The procedure was tested and works ok. Here is my code:
private void LoadReport()
{
try
{
MySqlParameter quote = new MySqlParameter();
quote = new MySqlParameter("quote", SqlDbType.VarChar);
quote.Value = quote_id_box.Text;
MySqlConnection con = new MySqlConnection(conSettings.ToString());
MySqlCommand cmd = new MySqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "project_report";
cmd.Parameters.Add(quote);
MySqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
dt.Load(dr);
cmd.ExecuteNonQuery();
Microsoft.Reporting.WinForms.ReportDataSource rds = new Microsoft.Reporting.WinForms.ReportDataSource("pr_DataSet", dt);
this.reportViewer1.LocalReport.DataSources.Add(rds);
this.reportViewer1.RefreshReport();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The dataTable is getting a response from MySQL and it has the right data in it but the problem is that the report won't show the information. It gives me
"the report source has not been defined"
Any ideas on what i'm doing wrong? This is my first report ever using report viewer. Any help would be greatly appreciated. Thanks

How to use openquery in c#

I have an openquery SQL script:
Select * from openquery([oak],'
SELECT LicenseKey, SUM(PaymentAmount)as Payments
FROM vw_ODBC_actv_Payments pt
WHERE MONTH(pt.EntryDate) = 2 and
YEAR(pt.EntryDate) = 2015
GROUP BY LicenseKey
')
When I run this from SSMS I can see that it returns expected n rows.
However when I'm firing this with the same connection properties to get the data in a DataSet for a C# console application:
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand pcmd= new SqlCommand();
DataSet ds= new DataSet();
OpenConnection();
pcmd.Connection = new SqlConnection("Data source=IP adress of the server;Initial Catalog=master; user ID=***; password=***");
cmd.CommandText = "Select * from openquery([oak],'" +
"SELECT LicenseKey, SUM(PaymentAmount)as Payments" +
"FROM vw_ODBC_actv_Payments pt " +
"WHERE MONTH(pt.EntryDate) = 2 and" +
"YEAR(pt.EntryDate) = 2015" +
"GROUP BY LicenseKey')";
try
{
da.SelectCommand = pcmd;
da.Fill(ds); //here comes the error
}
catch (Exception ex)
{
throw new Exception("DBUtils.ExecuteReader():" + ex.Message);
}
I'm getting an error like this:
The provider indicates that the user did not have the permission to
perform the operation. Now I need to do something with this issue
I'm just learning about openquery. Can anybody guide?
Firstly you're not opening the connection anywhere in your code hence the error. Second clean up your code with the using block. So assuming the query works as required you can do something like.
using(SqlConnection con = new SqlConnection("Connection String Here"))
{
string myQuery = "Your Query";
using(SqlCommand cmd = new SqlCommand(myQuery, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
con.Open();
sda.SelectCommand = cmd;
DataSet ds = new DataSet();
sda.Fill(ds);
}
}
}
Note: It would be a better if you stored the connectionString in your config file and read it in your code.

fill datagridview with content from .mdf

I am trying to fill a datagridview with content from a .mdf SQL Server database file (C# Windows Forms app)...
private void Companies_Load(object sender, EventArgs e)
{
load_table();
}
void load_table()
{
String DATA = Application.StartupPath + #"\data.mdf";
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + DATA + ";Integrated Security=True";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand("select * from Companies ;", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception uu)
{
MessageBox.Show(uu.Message);
}
}
I get nothing. DataGridView is empty. No errors...
Table name: Companies with 4 rows and 1 column...
I tried SQL statements like
select * from dbo.Companies ;
... still nothing
I changed data.mdf connection to full path c:/etc/etc ...
No luck.
Any simple solution is welcome :)
.mdf is a SQL Server data file, therefore you need to use the SQL Server client library, e.g. SqlConnection, SqlCommand and SqlDataAdapter.
What you're using now (MySqlConnection, MySqlCommand, MySqlDataAdapter) is for MySQL and won't work on a (Microsoft) SQL Server data file.

Creating Dataset Dynamically and passing to ReportViewer

all i did is just create a reportViewer in the form, then i have this code:
SqlConnection cn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=G:\I.S\C#\billingSystem\Store.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
private void Form1_Load()
{
runRptViewer();
cn.Open();
}
private void rptGetDataset()
{
DataSet ds = new DataSet();
ds.DataSetName = "dsNewDataSet";
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM NewBill", cn);
ds.GetXmlSchema();
da.Fill(ds);
ds.WriteXmlSchema(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xsd");
ds.WriteXml(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xml");
}
private DataTable getData()
{
DataSet dss = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM NewBill", cn);
da.Fill(dss);
DataTable dt = dss.Tables["NewBill"];
return dt;
}
private void runRptViewer()
{
this.reportViewer2.Reset();
//this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("Report.rdlc");
this.reportViewer2.LocalReport.ReportPath =(#"G:\I.S\Testoooooooo\Testoooooooo\Report1.rdlc");
ReportDataSource rds = new ReportDataSource("dsNewDataSet_NewBill", getData());
this.reportViewer2.LocalReport.DataSources.Clear();
this.reportViewer2.LocalReport.DataSources.Add(rds);
//this.reportViewer2.DataBind();
this.reportViewer2.LocalReport.Refresh();
}
}
i have two reportViewer the reportViewer1 work but in case the directory of the db has change it will not work, so thats why i try in another reportViewer, to make it work even if the directory of the db changed, i can just change the Connection string.
The problem is the report don't show anything, i think the problem in the code:
//this.ReportViewer1.LocalReport.ReportPath = Server.MapPath("Report.rdlc");
this is a windows form so there is no server, ive change it to:
this.reportViewer2.LocalReport.ReportPath =(#"G:\I.S\Testoooooooo\Testoooooooo\Report1.rdlc");
and this one dont work:
//this.reportViewer2.DataBind();
i cant understand this two lines, does it mean to create a Dataset1.xsd and Dataset1.xml, or just edit them.
ds.WriteXmlSchema(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xsd");
ds.WriteXml(#"G:\I.S\Testoooooooo\Testoooooooo\Dataset1.xml");
if possible i need a steps from creating every thing to codding that will be great.
How did you create your dataset? Is it SQL or from Objects in memory?
If you havent created a dataset, you do need to create one before the report can work properly. This might help: http://shrutikapoor-ubc.blogspot.com/2013/05/using-business-objects-in-report-viewer.html
To use the report viewer in your C# WinForm project add the following code to a button or inthe form_load:
string strConnectionString = "Data Source=(local);Initial Catalog=Projects_DB;Integrated Security=True";
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("sp_GetProject " + "'0660CAD6-6F1A-4D19-A1FD-17BF3655AC98'");
cmd.CommandType = CommandType.Text;
cmd.Connection = new SqlConnection (strConnectionString);
da.SelectCommand = cmd;
da.Fill(ds,"DataSet1");
reportViewer1.ProcessingMode = ProcessingMode.Local;
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds.Tables[0]));
reportViewer1.LocalReport.Refresh();
reportViewer1.RefreshReport();
Assuming that you have a stored procedure that accepts #ProjectID parameter. You have to set the cmd.CommandType = CommandType.Text if you pass these parameters along with the sql command. However, if you don't want to pass parameters just change the commandType to cmd.CommandType = CommandType.StoredProcedure.
Below is the stored procedure used in this example:
CREATE PROC [dbo].[sp_GetProject]
#ProjectID nvarchar(50)=NULL
AS
BEGIN
SELECT ProjectID, ProjectName FROM Projects
WHERE
(#ProjectID IS NULL) OR (ProjectID = #ProjectID)
END
Microsoft has a pretty good walkthrough here...
http://blogs.msdn.com/b/sqlforum/archive/2011/04/28/sql-reporting-services-ssrs-bind-dynamic-dataset-to-your-local-report-with-reportviewer.aspx

Categories