Error in adapter.fill function - c#

I am a beginner programmer.
I wrote the following code that shows an error in "adapter.fill(dt) ??????
this code must do the following steps:
1-connect to my dataset that has two fields :UserID,TrackID (2916 fields) 2-Read the dataset line by line and put the UserId of each recored to a url(instead of ). 3-Search through the webpage 4-if it finds the TrackId (exactly the same) which is related to UserId, add 1 to counter.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}

This is invalid:
"Select * from hidden.accdb"
hidden.accdb should be table name that contains the UserID and TrackID columns. not access database file name

Related

How to use DataTable from SQL Server in C#

I want to view this table in the list box in C#
enter image description here
I'm using this query to show the table
select
Chicken_Name, WithOrWithout_Name, Chicken_Price
from
Tbl_Add a
full outer join
tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID
full outer join
Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ;
And this code to put it in the list box in C#
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
This is the full 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 HABIBIS_GRILL
{
public partial class HabibisGrll : Form
{
SqlConnection connection;
string connectionString;
public HabibisGrll()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["HABIBIS_GRILL.Properties.Settings.HabibisGrilllDataBAseConnectionString"].ConnectionString;
}
private void Form1_Load(object sender, EventArgs e)
{
Chicken();
}
private void Chicken()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select Chicken_Name,WithOrWithout_Name,Chicken_Price from Tbl_Add a full outer join tbl_Chicken b ON b.Chicken_ID = a.Chicken_ID full outer join Tbl_WithORWithot c ON a.WorWO_ID = c.WithOrWothout_ID ; ", connection))
{
DataTable tbl_Chicken = new DataTable();
adapter.Fill(tbl_Chicken);
lst_SHowdata.DisplayMember = "Chicken_Name";
lst_SHowdata.ValueMember = "Chicken_ID";
lstSHowdata2.DisplayMember = "Chicken_Price";
lst_SHowdata.DataSource = tbl_Chicken;
lstSHowdata2.DataSource = tbl_Chicken;
}
}
}
}
The problem is I need to use one list box for each column, how to make them in one list box or do I use another tool ?
And how to put 2 or more tables in one datatable (adapter) ?
Thank you ^^"
first question:
you can use gridview for your query if you want to show more than 1 column from your query.
Second question:
and you can use DataSet to get more than 1 table in case you need.
check this:
string queryCustomer =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryCustomer , connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet , "Customers");
string queryOrders =
"SELECT OrderId, Date FROM dbo.Orders";
SqlDataAdapter adapterOrder = new SqlDataAdapter(queryOrders , connection);
adapterOrder.Fill(dataSet , "Orders");
//assume you have a GridView named myGridview.
//than set its DataSource to one of your DataSet tables.
myGridview.DataSource = dataSet.Tables[0] //customers will be the source

Storing Selected CheckedListBox Values in Database

I have two tables in my database. Let's say table A and table B. table A values are put in checkedlistbox. The selected values in checkedlistbox then are put into table B. I tried to make a code however it wont work. Do you have any idea on how to make this problem work?
thanks ahead guys.
by the way im using c#.
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 Npgsql;
namespace WindowsFormsApplication1
{
public partial class Form8 : Form
{
public Form8()
{
InitializeComponent();
this.Load += Form8_Load;
button2.Click += button2_Click;
}
private void Form8_Load(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("SELECT conname FROM condition", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
using (NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
da.Fill(dt);
((ListBox)checkedListBox1).DataSource = dt;
((ListBox)checkedListBox1).DisplayMember = "conname";
((ListBox)checkedListBox1).DisplayMember = "conid";
string[] condition = dt.Rows[0]["conname"].ToString().Split(',');
}
}
private void button2_Click(object sender, EventArgs e)
{
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
conn.Open();
cmd.Parameters.AddWithValue("#famid", checkedListBox1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data has been saved");
conn.Close();
}
}
}
You have to iterate through all the selected items:
//check if any item is selected
if (checkedListBox1.SelectedItems.Count > 0)
{
//connect to database
string connstring = ("Server=localhost;Port=5432;User Id=postgres;Password=021393;Database=postgres;");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
//loop through all selected items
foreach (object item in checkedListBox1.CheckedItems)
{
//convert item to string
string checkedItem = item.ToString();
//insert item to database
NpgsqlCommand cmd = new NpgsqlCommand("Insert into famhistory(famid) Values (#famid)", conn);
cmd.Parameters.AddWithValue("#famid", checkedItem); //add item
cmd.ExecuteNonQuery();
}
//close connection
conn.Close();
MessageBox.Show("Data has been saved");
}
Note: I am executing all insert commands in one open connection, because opening and closing connection frequently is not best practice.

compare the length of two variable

I am a beginner programmer.
I wrote following code and I want to compare the lenght of the Track ID (which is in my data set) with the Track ID (which is extracted from the web page) which both are highlighted.(my data set has two fields(user id-track id), i want to compare this track id with the track id which is return from web page)
I want to to it like:
if (client.Contains(Convert.ToString(TrackID))&&row["TrackID"].lenght=Track ID.lenght)
Thank you
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}
Why not do this?
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == Convert.ToString(TrackID).ToLower())
{
counter++;
}

read data from sqlite into C# then to sqlite

Reproducible Example:
sqlite db test3.s3db has one table with name "MathRec":
name score
Bill 2
Mary 3
John 3
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SQLite;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\Desktop\\dataset\\test3.s3db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
string selectSQL = "SELECT * FROM MathRec";
SQLiteCommand selectCommand = new SQLiteCommand(selectSQL, conread);
SQLiteDataReader dataReader = selectCommand.ExecuteReader();
DataSet ds = new DataSet();
DataTable dt = new DataTable("MathRec");
dt.Load(dataReader);
ds.Tables.Add(dt);
// Create a table in the database to receive the information from the DataSet
string fullPath2 = "C:\\Users\\\\Desktop\\dataset\\test4.s3db";
SQLiteConnection conwrite = new SQLiteConnection("Data Source=" + fullPath2);
conwrite.Open();
SQLiteCommand cmd = new SQLiteCommand(conwrite);
cmd.CommandText = "DROP TABLE IF EXISTS MathRec";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE TABLE MathRec(name text , score integer)";
cmd.ExecuteNonQuery();
SQLiteDataAdapter adaptor = new SQLiteDataAdapter("SELECT * from MathRec", conwrite);
adaptor.InsertCommand = new SQLiteCommand("INSERT INTO MathRec VALUES(:name, :score)", conwrite);
adaptor.InsertCommand.Parameters.Add("name", DbType.String, 0, "name");
adaptor.InsertCommand.Parameters.Add("score", DbType.Int32, 0, "score");
adaptor.Update(ds, "MathRec");
}
}
}
Questions:
Table MathRec is created in test4.s3db with column names: name and socre, but the table is empty with no records inserted.
Help is needed!
Please don't ask me why I am just copying one db to another, because I am testing one part of the code for a bigger project, where I will do calculations to the Dataset in the middle step in the future.
Thanks!
To simplify the question:
This works (use datatable and adapter to update the original sqlite table):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\data\\test.db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
SQLiteDataAdapter DB = new SQLiteDataAdapter("SELECT speed, dist FROM Cars2", conread);
DataSet DS = new DataSet();
DB.Fill(DS, "NewCars");
object[] rowVals = new object[2];
rowVals[0] = 10;
rowVals[1] = 20;
DS.Tables["NewCars"].Rows.Add(rowVals);
DB.InsertCommand = new SQLiteCommand("INSERT INTO Cars2 (speed, dist)
" + " VALUES (:speed, :dist)", conread);
DB.InsertCommand.Parameters.Add("speed", DbType.Double, 0, "speed");
DB.InsertCommand.Parameters.Add("dist", DbType.Double, 20, "dist");
DB.Update(DS, "NewCars");
}
}
}
And this works (create a new sqlite table from old one):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\data\\test.db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
SQLiteCommand cmd = new SQLiteCommand(conread);
cmd.CommandText = "DROP TABLE IF EXISTS Cars";
cmd.ExecuteNonQuery();
cmd.CommandText = "CREATE TABLE Cars (speed REAL , dist REAL)";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO Cars SELECT * from DS";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
}
But this one is what I wanted (use datatable and adapter to create new table in sqlite) and is not working:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.Data;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string fullPath = "C:\\Users\\data\\test.db";
SQLiteConnection conread = new SQLiteConnection("Data Source=" + fullPath);
conread.Open();
SQLiteDataAdapter DB = new SQLiteDataAdapter("SELECT speed, dist FROM Cars2", conread);
DataSet DS = new DataSet();
DB.Fill(DS, "NewCars");
object[] rowVals = new object[2];
rowVals[0] = 10;
rowVals[1] = 20;
DS.Tables["NewCars"].Rows.Add(rowVals);
SQLiteDataAdapter DB2 = new SQLiteDataAdapter("SELECT speed, dist FROM Cars3", conread);
DB2.InsertCommand = new SQLiteCommand("INSERT INTO Cars3 (speed, dist)
" + " VALUES (:speed, :dist)", conread);
DB2.InsertCommand.Parameters.Add("speed", DbType.Double, 0, "speed");
DB2.InsertCommand.Parameters.Add("dist", DbType.Double, 20, "dist");
DB2.Update(DS, "NewCars");
}
}
}
Please help!!!
I found the answer!
Adapter.Update can only be used to update the original table in the database and not to save the datatable in a new one. Please refer to the thread for answers:
C# Dataset to Access DB
Cheers!
The easiest way to copy one table to another database is to attach the second database to the first connection, and copy the data directly:
ATTACH '...\test4.s3db' AS 'test4';
DROP TABLE IF EXISTS test4.MathRec;
CREATE TABLE test4.MathRec(name text , score integer);
INSERT INTO test4.MathRec SELECT * FROM MathRec;
If you want to do calculations, you might be able to do them in SQL, in the SELECT statement.
If not, you have to read the data with a SELECT and then execute one INSERT statement for each record to be written. (In that case, you don't need the ATTACH.)

Is it possible to use the dataset generated dynamically in the report viewer?

I am new to Windows Desktop Application Development.
I want to print the bill in my application and I have used a report viewer control and placed two labels to display the Bill No and Party Name.
I am creating the dataset in code behind file in C#.
I am assigning the value of dataset cell to the text property of the label. My code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter da;
DataSet ds;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Bill\\dbBill.accdb");
string query = "select A.BillNo,A.BillType,A.TaxType,A.PartyName,B.Desc,B.Desc,B.HSNCode,B.Qty,B.Rate,(B.Qty*B.Rate) as Amount " +
"from BillMaster A inner join BillDetail B on B.BillNo=A.BillNo";
cn.Open();
cmd = new OleDbCommand(query, cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
// TODO: This line of code loads data into the 'dbBillDataSet.BillDetail' table. You can move, or remove it, as needed.
this.BillDetailTableAdapter.Fill(this.dbBillDataSet.BillDetail);
this.reportViewer1.RefreshReport();
}
private void reportViewer1_Load(object sender, EventArgs e)
{
lblBillNo.Text = ds.Tables[0].Rows[0]["BillNo"].ToString();
lblParty.Text = ds.Tables[0].Rows[0]["PartyName"].ToString();
}
}
}
How to assign the dataset values to the controls placed inside the report viewer control.
Please help me. Thanks in advance.
You wont be able to access DataSet instance ds inside of reportviewr_load. I would suggest you to make a function() which will return a DataSet and use that function() inside of the reportviewr_load.
private DataSet YourData()
{
cn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\Bill \\dbBill.accdb");
string query = "select
A.BillNo,A.BillType,A.TaxType,A.PartyName,B.Desc,B.Desc,B.HSNCode,B.Qty,B.Rate,
(B.Qty*B.Rate) as Amount " +
"from BillMaster A inner join BillDetail B on B.BillNo=A.BillNo";
cn.Open();
cmd = new OleDbCommand(query, cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
return ds;
}

Categories