Use combobox value as query value (VC# 2k8 / ADO SQLITE) - c#

I'm a newbie in VC# and ADO SQLITE...
I'm trying to change the content of a combobox according to the value present in another one...
My problem is here :
SQLiteCommand cmd3 = new SQLiteCommand("select distinct(ACTION) from ACTION_LIST where CATEGORY='comboBox1.text'", conn2);
What to use to do the job ? Here 'comboBox1.text' is see as a sentence not a variable...
Here is the code :
private void Form1_Load(object sender, EventArgs e)
{
using (SQLiteConnection conn1 = new SQLiteConnection(#"Data Source = Data\MRIS_DB_MASTER"))
{
conn1.Open();
SQLiteCommand cmd2 = new SQLiteCommand("select distinct(CATEGORY) from ACTION_LIST", conn1);
SQLiteDataAdapter adapter1 = new SQLiteDataAdapter(cmd2);
DataTable tbl1 = new DataTable();
adapter1.Fill(tbl1);
comboBox1.DataSource = tbl1;
comboBox1.DisplayMember = "CATEGORY";
adapter1.Dispose();
cmd2.Dispose();
}
using (SQLiteConnection conn2 = new SQLiteConnection(#"Data Source = Data\MRIS_DB_MASTER"))
{
conn2.Open();
SQLiteCommand cmd3 = new SQLiteCommand("select distinct(ACTION) from ACTION_LIST where CATEGORY='comboBox1.text'", conn2);
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd3);
DataTable tbl2 = new DataTable();
adapter2.Fill(tbl2);
comboBox2.DataSource = tbl2;
comboBox2.DisplayMember = "ACTION";
adapter2.Dispose();
cmd3.Dispose();
}
}
Thanks
regards

Use System.Data.SQLite.SQLiteParameter. Try this out. (I may have some syntax wrong because I'm not able to test this right now...but it should be similar)
From your code:
SQLiteCommand cmd3 = new SQLiteCommand("select distinct(ACTION) from ACTION_LIST where CATEGORY=#category", conn2);
cmd3.Parameters.Add(new SQLiteParameter("#category",comboBox1.Text));

comboBox1.Text is the label of the combobox, you need comboBox1.SelectedValue. You also need to do what aaron says and add a parameter.

Related

c# display Access Database in DataGridView

First of all, here is my code:
private void Form5_Load(object sender, EventArgs e)
{
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\Users\name\Documents\myprogramms\example.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores;
}
My goal is to display the data out of a MS Access Database. My codes has no error messages, but everytime I try to open the Data Grid View its completely empty.
your code snippet looks good. I cannot see any obvious issue.
Try to put breakpoint at the end of your method and check if datatable contains rows and rows contains any values in ItemArray.
Make sure your data_example DataGridView control is set AutoGenerateColumns = true (default) and check you have no other data source defined for your data_example DataGridView control. This code works for me.
private void Form1_Load(object sender, EventArgs e)
{
data_example.AutoGenerateColumns = true;
string strProvider = #"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = c:\aaa\CinemaBooking.accdb";
string strSql = "Select * from Booking";
using (OleDbConnection con = new OleDbConnection(strProvider))
{
using (OleDbCommand cmd = new OleDbCommand(strSql, con))
{
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
con.Open();
var scores = new DataTable();
da.Fill(scores);
data_example.DataSource = scores.DefaultView;
con.Close();
}
}
}
}
Maybe you can try to fill dataset with adapter and then use named table as datasource:
var dtSet = new DataSet();
da.Fill(dtSet, "Booking");
data_example.DataSource = dtSet.Tables["Booking"].DefaultView;

c# how to use Combobox.Value for a From Clause in a Sql query

Please can you assist me in a very weird request
I am building a form to represent a table in a datagridview.
I want to change the data that is bound to the datagridview when i select a different value in a combobox. I bound the event to a button.
i get an error when i run the code:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in query. Incomplete query clause.
the code i have is as follows.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand("Select * From #name ", con);
cmd.Parameters.AddWithValue("#name", comboBox1.SelectedValue);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
This code will help you:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.Text), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
you can not pass table name as parameter. you can build sql based on your value selection in your combobox. replace your code with this code and check.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ",comboBox1.SelectedValue), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
If you use Data Bound Items then use comboBox1.SelectedValue. If you use Unbound Mode then use comboBox1.SelectedItem.
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
//OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedValue.ToString(), con);
OleDbCommand cmd = new OleDbCommand("Select * From " + comboBox1.SelectedItem.ToString(), con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}
But not advice this way. You can use stored Procedure.
Try This:
private void Ok_button3_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = E:\database.accdb; Persist Security Info =False;");
string tableName = comboBox1.SelectedValue;
var builder = new SqlCommandBuilder();
string escapedTableName = builder.QuoteIdentifier(tableName);
OleDbCommand cmd = new OleDbCommand("Select * From " + escapedTableName , con);
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dt.TableName = "Project";
dataGridView1.DataSource = dt;
}

sql search query in c#

I'm trying to make a database search in my app where the user would choose the column and enter the search word and the result would come up in a dataviewgrid.
This is the code i've been working on, the problem is that nothing comes up and i'm pretty sure there are entries in the database. EDIT : it's a windows form application
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE #choice = #input", conn);
cmd.Parameters.AddWithValue("#choice", comboBox1.Text);
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
You cannot use a parameter to express the name of a column.
You should populate your combobox with the column names and set its DropDownStyle property to DropDownList (do not allow your user to type the name of the column) and then build your query
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = #input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
you forgot to bind the grid view with datasource
add this after data source
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
private void bunifuThinButton21_Click(object sender, EventArgs e)
{
SqlConnection connection = new SqlConnection();
connection.ConnectionString = (#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\albasheer\Desktop\games\my_school\my_school\school.mdf;Integrated Security=True;User Instance=True");
connection.Open();
string sql = "select name,id,stage,age,cost from STUDENT where stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
SqlCommand command = new SqlCommand(sql, connection);
DataTable table = new DataTable();
adapter.Fill(table);
var dt = from t in table.AsEnumerable()
select new
{
id = t.Field<int>("id"),
Name = t.Field<string>("name"),
};
bunifuCustomDataGrid1.DataSource = dt.ToList();
}

Populate a datagridview with sql query results

I'm trying to present query results, but I keep getting a blank data grid.
It's like the data itself is not visible
Here is my code:
private void Employee_Report_Load(object sender, EventArgs e)
{
string select = "SELECT * FROM tblEmployee";
Connection c = new Connection();
SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
What's wrong with this code?
Here's your code fixed up. Next forget bindingsource
var select = "SELECT * FROM tblEmployee";
var c = new SqlConnection(yourConnectionString); // Your Connection String here
var dataAdapter = new SqlDataAdapter(select, c);
var commandBuilder = new SqlCommandBuilder(dataAdapter);
var ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = ds.Tables[0];
String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;
You don't need bindingSource1
Just set dataGridView1.DataSource = table;
Try binding your DataGridView to the DefaultView of the DataTable:
dataGridView1.DataSource = table.DefaultView;
This is suppose to be the safest and error pron query :
public void Load_Data()
{
using (SqlConnection connection = new SqlConnection(DatabaseServices.connectionString)) //use your connection string here
{
var bindingSource = new BindingSource();
string fetachSlidesRecentSQL = "select top (50) * from dbo.slides order by created_date desc";
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(fetachSlidesRecentSQL, connection))
{
try
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource.DataSource = table;
recent_slides_grd_view.ReadOnly = true;
recent_slides_grd_view.DataSource = bindingSource;
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message.ToString(), "ERROR Loading");
}
finally
{
connection.Close();
}
}
}
}
You may get a blank data grid if you set the data Source to a Dataset that you added to the form but is not being used. Set this to None if you are programatically setting your dataSource based on the above codes.
You may try this sample, and always check your Connection String, you can use this example with or with out bindingsource you can load the data to datagridview.
private void Employee_Report_Load(object sender, EventArgs e)
{
var table = new DataTable();
var connection = "ConnectionString";
using (var con = new SqlConnection { ConnectionString = connection })
{
using (var command = new SqlCommand { Connection = con })
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
try
{
command.CommandText = #"SELECT * FROM tblEmployee";
table.Load(command.ExecuteReader());
bindingSource1.DataSource = table;
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
catch(SqlException ex)
{
MessageBox.Show(ex.Message + " sql query error.");
}
}
}
}
you have to add the property Tables to the DataGridView Data Source
dataGridView1.DataSource = table.Tables[0];
if you are using mysql this code you can use.
string con = "SERVER=localhost; user id=root; password=; database=databasename";
private void loaddata()
{
MySqlConnection connect = new MySqlConnection(con);
connect.Open();
try
{
MySqlCommand cmd = connect.CreateCommand();
cmd.CommandText = "SELECT * FROM DATA1";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagrid.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Years late but here's the simplest for others in case.
String connectionString = #"Data Source=LOCALHOST;Initial Catalog=DB;Integrated Security=true";
SqlConnection cnn = new SqlConnection(connectionString);
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblEmployee;", cnn);
DataTable data = new DataTable();
sda.Fill(data);
DataGridView1.DataSource = data;
Using DataSet is not necessary and DataTable should be good enough. SQLCommandBuilder is unnecessary either.
I think this professional way to Write from start, but you can use this code with MySQL bout I think they both are the same:
1/
using System.Data; AND using MySql.Data.MySqlClient;
2/
MySqlConnection con = new MySqlConnection("datasource=172.16.2.104;port=3306;server=localhost;database=DB_Name=root;password=DB_Password;sslmode=none;charset=utf8;");
MySqlCommand cmd = new MySqlCommand();
3/
public void SetCommand(string SQL)
{
cmd.Connection = con;
cmd.CommandText = SQL;
}
private void FillGrid()
{
SetCommand("SELECT * FROM `transport_db`ORDER BY `id` DESC LIMIT 15");
DataTable tbl = new DataTable();
tbl.Load(cmd.ExecuteReader());
dataGridView1.DataSource = tbl;
}
for oracle:
var connString = new ConfigurationBuilder().AddJsonFile("AppSettings.json").Build()["ConnectionString"];
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connString;
connection.Open();
var dataAdapter = new OracleDataAdapter("SELECT * FROM TABLE", connection);
var dataSet = new DataSet();
dataAdapter.Fill(dataSet);

How do i bind data source to a ComboBox?

So i currently have two combo boxes. One Being Manufacture the other being model. My sql query looks like this "Select Distinct Model From sheet1 where (Manufacture =#Manufacture)" this works when i execute it and if i were to fill a datagridtable. But if i try to place this into a combobox i get System.data.d...... etc for my selections. How can i just have it show the values instead of all this. What am i doing wrong?
private void ManuComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
string manu = comboBox3.Text;
string conStr = "Data Source=CA-INVDEV\\RISEDB01;Initial Catalog=RISEDB01; Integrated Security=True";
string sqlcmd = "SELECT DISTINCT Model FROM Sheet1 WHERE (Manufacture =#Manufacture)";
using (SqlConnection conn = new SqlConnection(conStr))
{
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dr.Close();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource3.DataSource = table;
ModelComboBox.DataSource = bindingSource3;
}
}
}
Can you give this a try?
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sqlcmd, conn);
cmd.Parameters.AddWithValue("#Manufacture", manu);
SqlDataReader dr = cmd.ExecuteReader();
IList<string> modelList = new List<string>()
while (dr.Read())
{
modelList.add(dr[0].ToString());
}
ModelComboBox.DataSource = modelList;
}
If you have set the display member like:
ModelComboBox.DataSource = bindingSource3;
ModelComboBox.DisplayMember = "ColumnName";
And it still shows funny values, what are the values that it shows exactly?
Note, in a toolstrip it looks like you may have to also do:
ModelComboBox.BindingContext = this.BindingContext;
here is a reference
Try adding
ComboBox1.ItemsSource = bindingSource3
if this is your answer then mark it as answer

Categories

Resources