Getting table data into Gridview in C# (SQLite) is not working - c#

I want to show my data that I have stored in a SQLite database in an ASP.net page which I code in C#.
I searched a lot on the internet and in my previous question someone showed me a really helpfull article. I used the code but it still doesn't work.
What I want is to get the first three columns in my gridview. So "woord", "vertaling" and "gebruiker" from the table "tbWoorden" should be displayed in the gridview.
This is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Scripts_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
string connectionString =
#"Data Source=C:/Users/elias/Documents/Visual Studio 2017/WebSites/WebSite7/App_Data/overhoren.db";
using (var conn = new System.Data.SQLite.SQLiteConnection(connectionString))
{
conn.Open();
DataSet dsTest = new DataSet();
// Create a SELECT query.
string strSelectCmd = "SELECT woord,vertaling,gebruiker FROM tbWoorden";
// Create a SqlDataAdapter object
// SqlDataAdapter represents a set of data commands and a
// database connection that are used to fill the DataSet and
// update a SQL Server database.
SqlDataAdapter da = NewMethod(conn, strSelectCmd);
// Fill the DataTable named "Person" in DataSet with the rows
// returned by the query.new n
da.Fill(dsTest, "tbWoorden");
// Get the DataView from Person DataTable.
DataView dvPerson = dsTest.Tables["tbWoorden"].DefaultView;
// Set the sort column and sort order.
dvPerson.Sort = ViewState["SortExpression"].ToString();
// Bind the GridView control.
grdMijnLijsten.DataSource = dvPerson;
grdMijnLijsten.DataBind();
using (var command = new System.Data.SQLite.SQLiteCommand(conn))
{
command.Connection = conn;
command.CommandText =
#"SELECT[vertaling], [woord] FROM[tbWoorden] WHERE[woord] = 'ans'";
using (var reader = command.ExecuteReader())
{
string test = "";
}
}
}
}
private static SqlDataAdapter NewMethod(System.Data.SQLite.SQLiteConnection conn, string strSelectCmd)
{
return new SqlDataAdapter(strSelectCmd, conn);
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void grdMijnLijsten_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
The error I get is: cannot convert from 'System.Data.SQLite.SQLiteConnection' to 'string'.
The part that causes the error is the conn string in the NewMethod:
private static SqlDataAdapter NewMethod(System.Data.SQLite.SQLiteConnection conn, string strSelectCmd)
{
return new SqlDataAdapter(strSelectCmd, conn);
}
What do I have to change?
Thanks in advance, Elias

You have to use SQLiteDataAdapter (from the SQLite family) instead of SqlDataAdapter (which is part of the SQLClient family)

Related

Chart COUNT Query C#?

Kinda new to C#, I'm a bit confused with this issue I encountered in my codes for a school assignment. Trying to make a Room Activity chart in a winform for a school project where the SQL COUNT query I input counts the rows that have the value 'Room Activity' under the Event column but for some odd reason, I receive an ArgumentException wasn't handled error that tells me Column with name 'Event' was not found.
What am I doing wrong with my code?
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Configuration;
using System.Data.SqlClient;
namespace Database_Chart_test
{
public partial class Form1 : Form
{
string strConnectionString = ConfigurationManager.ConnectionStrings["Database_Chart_test.Properties.Settings.LibrarySystemConnectionString"].ConnectionString;
public Form1()
{
InitializeComponent();
}
private void Activitychart_Click(object sender, EventArgs e)
{
}
private void RoomChart()
{
SqlConnection con = new SqlConnection(strConnectionString);
DataSet ds = new DataSet();
con.Open();
SqlDataAdapter adapt = new SqlDataAdapter("SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'", con);
adapt.Fill(ds);
Activitychart.DataSource = ds;
Activitychart.Series["WithActivity"].XValueMember = "Event";
Activitychart.Series["WithActivity"].YValueMembers = "Event";
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'librarySystemDataSet1.RoomsBooking' table. You can move, or remove it, as needed.
this.roomsBookingTableAdapter.Fill(this.librarySystemDataSet1.RoomsBooking);
// TODO: This line of code loads data into the 'librarySystemDataSet.Log' table. You can move, or remove it, as needed.
this.logTableAdapter.Fill(this.librarySystemDataSet.Log);
RoomChart();
}
}
}
After SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity' executed, it will return a table with 1 column and 1 row (the count number).
Query result:
So the cause of the ArgumentException is that there is no column named Event in ds.Tables[0].
If you want to get the count, just call ExecuteScalar Method
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
string strSQL = "SELECT COUNT(*) FROM Log WHERE Event = 'Room Activity'";
SqlCommand cmd = new SqlCommand(strSQL, conn);
conn.Open();
int count = (int)cmd.ExecuteScalar();
// add data point
Activitychart.Series["WithActivity"].Points.AddXY("Event", count);
Console.WriteLine("The count is {0}", count);
}
In addition, according to the code you provided, you are trying to use Event(a string) as YValueMembers. This does not seem reasonable. Generally, YValueMembers should be of numeric type.

Insert does not working on Service Based Database in C#

I have created a service based database in visual studio 2017. It works with a select statement but INSERT statement doesn't work. Here is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace RestaurantApp
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\SerinCafe.mdf;Integrated Security=True");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Product (Id, ProductDescription, UnitPrice, SystemDate) Values (1,'Çay', 1, '01.01.2017')", conn);
cmd.ExecuteNonQuery();
SqlCommand cmd1 = new SqlCommand("SELECT * FROM Product", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
I saw the same problem on different topics but there wasn't a clear solution that applies for me.
EDIT: On the SQL Server Object Explorer there is another database under the folder debug/bin. Now I checked it and I saw that data is inserted as I wanted. But it doesn't stay same. I changed the sql query as id = 3 and checked again. Previous data has gone. Newly inserted data is only there.
I have tested the code it works fine.Make sure you provided the connection string correctly.

method is not being called by application

My method is not being called by my application. I've used breakpoints and it's never initiated in the code. I'm building a C# Windows Forms application using an Azure Database, but the DataGridView is never being filled neither is the code being called at all... I have noooo clue whatsoever why..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace MyWinFormsProj
{
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
}
//Connection String
string cs = ConfigurationManager.ConnectionStrings
["MyConnetion"].ConnectionString;
// Load all employees
private void dataEmployees_Load()
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}
// Crate company
private void createCompany_Click_1(object sender, EventArgs e)
{
if (textBoxCompanyName.Text == "")
{
MessageBox.Show("Fill out information");
return;
}
using (SqlConnection con = new SqlConnection(cs))
{
//Create SqlConnection
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into dbo.Company (companyName)
values(#companyName)", con);
cmd.Parameters.AddWithValue(
"#companyName", textBoxCompanyName.Text);
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
MessageBox.Show("Grattis! Du har skapat ett företag");
}
}
}
}
The second method is working and is doing what it is supposed to do, but the first one is never called..
you need to set an event handler on the gridView onLoad and pass this method to the handler
public void GridView_OnLoad(object sender, EventArgs e)
{
dataEmployees_Load();
}
You need to fix your method signature to look like this:
private void dataEmployees_Load(object sender, EventArgs e)
Then, in your GirdView, you need to set this function as handler for event "onload":
OnLoad="dataEmployees_Load"
Thank you guys for your answers it helped my solve the problem. Like you were saying the problem was in the method not being called. So I called it directly on initiliazeComponent like this.
public partial class CompanyForm : Form
{
public CompanyForm()
{
InitializeComponent();
Load += new EventHandler(dataEmployees_Load); //Added this code
}
// Load all employees
private void dataEmployees_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cs))
{
con.Open();
SqlCommand cmd = new SqlCommand
(
"Select fname,ename FROM dbo.Users", con
);
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataEmployees.DataSource = dt;
}
}

C# ASP.NET - SImplify number of SQL queries written in code

Here's a little background on what I'm doing...
I'm writing a C# web app. On the main page, I have a data input form with about 25 individual Dropdownlists. I created a table called options, and it's pretty simple (ID, Category, Option). Each option I create is categorized so my query will only include options that match the category I'm looking up. Each Category matches one of the 25 Dropdownlists I need to populate.
So I'm able to get a few of these populated on the form and they work great. I'm concerned that the re-writing of this code (with slight variation of the DDlist name and category name) will cause the code to be much longer. Is there a way I can create a class of it's own and pass parameters to the class so it only returns me data from the correct category and populates the correct Dropdownlist? Here's some sample code I have so far for 2 DD fields. The DDStationList and DDReqeustType are the names of 2 of the 25 Dropdownlists I have created:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Drawing;
namespace TEST
{
public partial class _Default : Page
{
//Main connection string
string SqlConn = ConfigurationManager.AppSettings["SqlConn"];
string qryRequestType = ConfigurationManager.AppSettings["qryRequestTypes"];
string qryStationNumbers = ConfigurationManager.AppSettings["qryStationNumbers"];
protected void Page_Load(object sender, EventArgs e)
{}
protected void BtnAddNew_Click(object sender, EventArgs e)
{
//GET Request Types
DataTable RequestTypes = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryRequestType, Conn);
adapter.Fill(RequestTypes);
DDRequestType.DataSource = RequestTypes;
DDRequestType.DataTextField = "Option";
DDRequestType.DataValueField = "Option";
DDRequestType.DataBind();
}
// Get Stations
DataTable Stations = new DataTable();
SqlConnection Conn = new SqlConnection(SqlConn);
{
SqlDataAdapter adapter = new SqlDataAdapter(qryStationNumbers, Conn);
adapter.Fill(Stations);
DDStationList.DataSource = Stations;
DDStationList.DataTextField = "Option";
DDStationList.DataValueField = "Option";
DDStationList.DataBind();
}
}
protected void BtnSubmit_Click(object sender, EventArgs e)
{
//More stuff to do here for submit code
}
}
}
Example queries from my config file that correspond to above code:
SELECT [Option] FROM Table WHERE Category = 'RequestType';
SELECT [Option] FROM Table WHERE Category = 'Station';
So, is it possible I can create a class that I can pass the Option's Category into that runs the query Like this:
SELECT [Option] FROM Table WHERE Category = #Category;
...and then populate the correct Dropdownlist (need to do this 25 times)?
If I'm not clear on my question, I'll be happy to explain further.
Why not create a stored procedure instead?
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_GetCategory", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
OR include the parameter
string sql = "SELECT [Option] FROM Table WHERE Category = #Category";
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd= new SqlCommand(sql, con)) {
cmd.Parameters.Add("#Category", SqlDbType.VarChar).Value = txtCategory.Text;
con.Open();
var results = cmd.ExecuteReader();
}
}
EDIT
class Category
{
/* properties */
/* method */
public List<Category> GetCategory(string selectedCategory)
{ /* Method statements here */ }
}

C# Crystal Report Warnings The report you requested requires further information

I use C#.NET (WebApp) VS 2008 SP1
I want click next page from crystal report v.10.5.3700 (Framework 3.5) but it's show input data to next page
The report you requested requires further information
Server name:
Database name:
User name:
Password:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Transactions;
using System.Drawing;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using CrystalDecisions.Web;
using CrystalDecisions.CrystalReports;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using CrystalDecisions.ReportSource;
namespace testReport
{
public partial class _cldClass : System.Web.UI.Page
{
SqlConnection objConn = new SqlConnection();
SqlCommand objCmd = new SqlCommand();
SqlDataAdapter dtAdapter = new SqlDataAdapter();
SqlConnection Conn;
DataSet ds = new DataSet();
DataTable dt = null;
string strConnString = WebConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
string strSQL = null;
public string userDB
{
get { return WebConfigurationManager.AppSettings["userDB"]; }
}
public string pwdDB
{
get { return WebConfigurationManager.AppSettings["pwdDB"]; }
}
public string srvDB
{
get { return WebConfigurationManager.AppSettings["srvDB"]; }
}
public string dbName
{
get { return WebConfigurationManager.AppSettings["dbName"]; }
}
//protected void Page_Load(object sender, EventArgs e)
//{
//}
protected void Page_Init(object sender, EventArgs e)
{
TextBox2.Text = DateTime.Now.ToString("yyyy-MM-dd", new CultureInfo("en-US"));
Conn = new SqlConnection(strConnString);
Conn.Open();
if (Conn.State == ConnectionState.Open)
{
this.Label1.Text = "Connected";
}
else
{
this.Label1.Text = "Connect Failed";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
strSQL = "SELECT * FROM fTime WHERE fDate='" + TextBox2.Text + "'";
objConn.ConnectionString = strConnString;
var _with1 = objCmd;
_with1.Connection = objConn;
_with1.CommandText = strSQL;
_with1.CommandType = CommandType.Text;
dtAdapter.SelectCommand = objCmd;
dtAdapter.Fill(ds, "cReport");
dt = ds.Tables[0];
dtAdapter = null;
objConn.Close();
objConn = null;
ReportDocument rpt = new ReportDocument();
rpt.Load(Server.MapPath("Report\\CrystalReport.rpt"));
rpt.SetDataSource(dt);
rpt.SetDatabaseLogon(userDB, pwdDB, srvDB, dbName);
CrystalReportViewer1.ReportSource = rpt;
CrystalReportViewer1.RefreshReport();
}
}
}
Thanks for your time :)
Normally you need to enter these informations when you created the report document directly from a database, that means when you used the report wizard and selected a table from the database. The report document itself contains the connection information to that data source but don't saves the logon information.
To overcome this you may create a typed dataset first from your database table you like to use in the report. Then create a report document and use the wizard to set the dataset (not the database table directly) as data source for your report. In your code you may then fill the dataset and just pass it to the report.
I ran into this today, and the reason I got the error was because I didn't have the correct provider installed on my server.
What I did was this:
CrystalReportViewer1.EnableDatabaseLogonPrompt = false;
That gave me a new error: Logon failed. Details: ADO Error Code: 0x Source: ADODB.Connection Description: Provider cannot be found. It may not be properly installed
After that, I checked the OLE DB provider in the report. Installing the SQL Native Client tools fixed the problem.

Categories