Sqlite error (DataGrid) - c#

I do not know how to fix the Problem.
It's a sqlite query that should give the requested data record in the DataGrid.
When I enter numbers, it works!
But not when i enter letter's.
SQLite error no such column: Example
My Code :
SQLiteConnection connection = new SQLiteConnection();
connection = new SQLiteConnection("Data Source=Database.s3db;Version=3;New=False;Compress=True;");
SQLiteCommand command = new SQLiteCommand(connection);
SQLiteDataAdapter DB;
DataSet DS = new DataSet();
DataTable DT = new DataTable();
connection.Open();
command = connection.CreateCommand();
string CommandText = "select Example from Lists where Example =" + textBox.Text ;
DB = new SQLiteDataAdapter(CommandText, connection);
DS.Reset();
DB.Fill(DS);
DT = DS.Tables[0];
Grid.DataSource = DT;
connection.Close();

If you are sure that Example exist in your table Lists and its type is of char, nvarchar or other character type then wrap your TextBox.Text in single quote like this
select Example from Lists where Example ='" + textBox.Text +"'" ;
However, try always to use parameter in your query.

Related

C# Datagridview cannot find table 0

This is my code:
SqlConnection connection = new SqlConnection(MyConnectionString2);
SqlCommand cmd2;
connection.Open();
try
{
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
}
catch (Exception)
{
throw;
}
TxbAddEmailUser.Clear();
The problem is that my program gives me the error:
System.IndexOutOfRangeException: cannot find tabel 0;
this is my database:
table: tbl_EmailAdress
column: id, int, NOT NULL
column: Email, char(10), NULL
The insert query works, what am I doing wrong?
"Cannot find table 0" indicates that DataSet has empty tables at the first index (0), so that you can't assign data source from it.
The main problem is you're using INSERT command here:
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress);");
INSERT command is not intended to return any results for SqlDataAdapter, you need to use ExecuteNonQuery:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (#EmailAddress)");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
cmd2.ExecuteNonQuery();
Note that ExecuteNonQuery only returns affected rows (i.e. 1 row), and you can't assign dataGridView1.DataSource to a single integer value.
If you want to use SqlDataAdapter, you need to use SELECT statement like this example:
cmd2 = connection.CreateCommand();
cmd2.CommandText = ("SELECT * FROM tbl_EmailAdress WHERE Email = #EmailAddress");
cmd2.Parameters.Add("#EmailAddress", SqlDbType.NVarChar);
cmd2.Parameters["#EmailAddress"].Value = TxbAddEmailUser.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
adap.Fill(ds); // fill the data table from adapter
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0]; // this time the first table is not null or empty
dataGridView1.DataSource = bs;
Similar issue:
Cannot find table 0 error in C#
No need of doing this ,
SqlDataAdapter adap = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dataGridView1.DataSource = bs;
just use
cmd2.ExecuteNonQuery();

Filtering by user input getting error message can not get table 0

I have wrote code following a tutorial posted here
http://csharp.net-informations.com/datagridview/csharp-datagridview-filter.htm
However I keep getting the error "Cannot find table 0", I have tried several things but none have worked
i have posted the code in my form load and the button to start the process
string connectionString = "server=localhost;user id=root;database=epas=";
string sql = "SELECT * FROM pricing sterling";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, con);
con.Open();
dataadapter.Fill(ds, "pricing table");
con.Close();
dataGridView1.DataSource = ds.Tables[0];
And the button
DataView dv;
dv = new DataView(ds.Tables[0], "ID = '21' ", "type Desc", DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;
Remove the spaces from the name of the datatable in
dataadapter.Fill(ds, "pricingtable");

Displaying rows from table into datagridview with matched column value

I have a list of string which contain names and a database table what i want to do is to display the rows from the table in datagridview. All rows which contain the name column value same as any of the list item will be displayed into datagrid view.I wrote the code for this using for loop but it is showing only last matched row in datagridview.
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FacesDatabase.mdb";
DBConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DBConnection;
for(i=0;i<MatchName.ToArray().Length;i++)
{
string query = "Select FaceID,FaceName,RollNo,FaceImage from " + tableName + " where FaceName='" + MatchName[i].ToString() + "'";
command.CommandText = query;
OleDbDataAdapter da=new OleDbDataAdapter(command);
DataTable dt=new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
DBConnection.Close();
You can use the IN SQL key word:
DBConnection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FacesDatabase.mdb";
DBConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DBConnection;
string query = "Select FaceID,FaceName,RollNo,FaceImage from " + tableName + " where FaceName IN ('"+ string.Join("','",MatchName.ToArray())+ "')";
command.CommandText = query;
OleDbDataAdapter da=new OleDbDataAdapter(command);
DataTable dt=new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
DBConnection.Close();
In your example what you're doing is querying the db for each "MatchName" (whatever that is) and for every resultset you're getting back you're assigning it as the datagrid's datasource. Therefore you're only seeing the last resultset since you're overwriting previous results.
Using the IN key word you're only hitting the db once and binding the grid to the data source once.
I also recommend using command parameters instead of building your query they way you are using string concatenation.
You are overwriting your gridview datasource. You can also do something like,
dataGridView1.DataSource = null;
for (i = 0; i < MatchName.ToArray().Length; i++)
{
string query = "Select FaceID,FaceName,RollNo,FaceImage from " + tableName + " where FaceName='" + MatchName[i].ToString() + "'";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
if (dataGridView1.DataSource != null)
{
DataTable dt2 = (DataTable)dataGridView1.DataSource;
dt.Rows.Cast<DataRow>().ToList().ForEach(x => dt2.ImportRow(x));
dt = dt2;
}
dataGridView1.DataSource = dt;
}

ms access database connection in a datagridview

What is the error of this code
connect = new OleDbConnection(coo);
connect.Open();
command.Connection = connect;
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter("SELECT * FROM Items where itemno = '" + textBox1.Text + "'", connect);
ODA.Fill(dt);
dataGridView1.DataSource = dt;
after I run it, this is what happened
"Data type mismatch in criteria expression"
What should I do?
itemno is integer, that is why you are getting the error, remove the single quotes around the value. But, More importantly, Use Parameters with your query. You are prone to SQL Injection
using (var connect = new OleDbConnection(coo))
{
using (OleDbCommand command = new OleDbCommand("SELECT * FROM Items where itemno = ?", connect))
{
command.Parameters.Add(new OleDbParameter("#p1", OleDbType.Integer)
{
Value = textBox1.Text
});
DataTable dt = new DataTable();
OleDbDataAdapter ODA = new OleDbDataAdapter(command);
ODA.Fill(dt);
dataGridView1.DataSource = dt;
}
}
Couple of things to add:
Enclose your Command and Connection object in using statement.
You don't have to explicitly open a connection with DataAdapter. It will open the connection to the database.
OleDB uses positional parameter instead of named parameter

OLEDB Parameterized Query

public void LoadDB()
{
string FileName = #"c:\asdf.accdb";
string query = "SELECT ID, Field1 FROM Table1 WHERE ID=? AND Field1=?";
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileName;
OleDbConnection odc = new OleDbConnection(strConn);
dAdapter = new OleDbDataAdapter();
OleDbCommand cmd = new OleDbCommand(query,odc);
cmd.Parameters.Add("?", OleDbType.Integer, 5).Value = 1234;
cmd.Parameters.Add("?", OleDbType.BSTR, 5).Value ="asdf";
dAdapter.SelectCommand = cmd;
ds = new DataSet();
dAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
I'm trying to use parametrized query to bind the access file into the datagridview. It finds the column names fine, but the contents are empty.
How can I fix this issue?
Here is an example of how the parameterized queries work with CSharp, OleDB.
try
{
connw.Open();
OleDbCommand command;
command = new OleDbCommand(
"Update Deliveries " +
"SET Deliveries.EmployeeID = ?, Deliveries.FIN = ?, Deliveries.TodaysOrders = ? , connw);
command.Parameters.Add(new OleDbParameter("#EMPID", Convert.ToDecimal(empsplitIt[1])));
command.Parameters.Add(new OleDbParameter("#FIN", truckSplit[1].ToString()));
command.Parameters.Add(new OleDbParameter("#TodaysOrder", "R"));
catchReturnedRows = command.ExecuteNonQuery();//Commit
connw.Close();
}
catch (OleDbException exception)
{
MessageBox.Show(exception.Message, "OleDb Exception");
}
This will work with any sql statement, you must assign the question mark "?" to each parameter, and then below you must create the parameters and add them in the order of how you laid out the question marks to get the right data into the right field.
In my test program, the ds.Tables[0].Rows.Count datatable actually had 1 row returned (as there was one row in my test database that matched the query itself). If you put a break on this line you should be able to see whether or not data is getting into the datatable in the first place. Try this:
dataGridView1.DataSource = ds.Tables[0];
What does the front end binding of dataGridView1 look like? Running the query in Access could shed some light on the situation too.
Try without specifying column size in parameters:
cmd.Parameters.Add("?", OleDbType.Integer).Value = 1234;
cmd.Parameters.Add("?", OleDbType.BSTR).Value ="asdf";

Categories