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 MySql.Data.MySqlClient;
namespace ICT_Assigment_3
{
public partial class search : Form
{
public search()
{
InitializeComponent();
}
DataTable dbdataset;
private void button1_Click(object sender, EventArgs e)
{
string constring = "datasource=localhost;port=3306;username=root;password=password";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(" select BookName,Publisher,Category,Edition,Year,Location from library.add_update ;", conDataBase);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDataBase;
dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
DataView DV = new DataView(dbdataset);
DV.RowFilter = string.Format("BookName LIKE '%{0}%'", search_box.Text);
dataGridView1.DataSource = DV;
}
}
}
I have done the search function, but it just can search my database by name, how to add another column, like publisher, i type the name it will also show the book same as category, location etc. Can anyone help me to improve this? Thank you
I highly recommend you to use a parameterized query o build it dynamically:
private DataTable FilterRecords()
{
bool where_set = false;
DataTable table = new DataTable();
string constring = "datasource=localhost;port=3306;username=root;password=password";
string commandText = "select BookName, Publisher, Category, Edition, Year,"
+ "Location from library.add_update "
+ "where "
// build your own filters
//
if (filter_by_name)
{
commandText += "name like '%" + varName + "%'";
where_set = true;
}
if (filter_by_publisher)
{
if (where_set) commandText += " and ";
commandText += "name like '%" + varName + "%'";
where_set = true;
}
using (MySqlConnection connection = new MySqlConnection(constring))
{
MySqlDataAdapter adp = new MySqlDataAdapter();
adp.SelectCommand = new MySqlCommand(commandText, connection);
adp.Fill(table);
}
return table;
}
Take a look, you must modify filters.
Add a function like that in you class and assign it to the bindigsource of the datagrid every time you want to filter some records. Use some variable to tell the function what you want to filter, or pass a filter as a function parameter and add it to the commandText;
DataGrid.DataSource = FilterRecords();
Related
I am very new to coding and am trying to learn C# through little project.
I spent a week or more trying to find solution but although there is many threads, none of them made sense for me and couldn't get it to work.
I have a Form with a DataGridView and I want to create 6 ComboBoxes to filter it. All with same data source.
I managed so far to get DataGridView working with one ComboBox but don't know how to add more of them.
My code:
using System.Data;
using System.Data.SqlClient;
public partial class frmEmpList : Form
{
private void frmEmpList_Load(object sender, EventArgs e)
{
this.PopulateCombobox();
this.PopulateDataGridView();
}
private void PopulateCombobox()
{
string qry = "SELECT DISTINCT LastName FROM Employees";
string constr = #"Data Source=DESKTOP-Q2B3UUH\SQLEXPRESS;Initial Catalog=PeopleManager;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
using (SqlDataAdapter sda = new SqlDataAdapter(qry, con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
DataRow row = dt.NewRow();
row[0] = "";
dt.Rows.InsertAt(row, 0);
cbLastName.DataSource = dt;
cbLastName.DisplayMember = "LastName";
cbLastName.ValueMember = "LastName";
}
}
private void PopulateDataGridView()
{
string query = "SELECT EmpID, FirstName, LastName, Role, Grade, Dept, Shift FROM Employees";
query += " WHERE LastName = #LastName";
query += " OR ISNULL(#LastName, '') = ''";
string constr = #"Data Source=DESKTOP-Q2B3UUH\SQLEXPRESS;Initial Catalog=PeopleManager;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#LastName", cbLastName.SelectedValue);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
dgEmpList.DataSource = dt;
}
}
}
private void cbLastName_SelectionChangeCommitted(object sender, EventArgs e)
{
this.PopulateDataGridView();
}
}
I would change ("#LastName", cbLastName.SelectedValue) to ("#LastName", string.IsNullOrWhiteSpace(cbLastName.SelectedValue as string) ? DBNull.Value : ((string)cbLastName.SelectedValue).Trim())
Then
query += " WHERE LastName = #LastName";
query += " OR ISNULL(#LastName, '') = ''";
To
query += " WHERE (#LastName IS NULL OR LastName = #LastName)";
If you need more filters for your query just add more filters like this
query += " AND (#FooBar IS NULL OR FooBar = #FooBar)";
You can also create dynamic script by only including filters you need in your script. First filter needs to use WHERE and others AND
I've been practicing with ADO.NET and SQL Server in a Windows Forms application, but I can't get table data into a DataGridView on the press of a button.
There are no errors and I make server connection checking. I have corresponding database and table name with some data in it.
Any ideas what I am doing wrong?
Here is code from the button:
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "Server=DESKTOP-FV268LU;Database=ado_database;Integrated Security=true";
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
if (myConnection.State == ConnectionState.Open)
label1.Text = "YES!";
else if (myConnection.State != ConnectionState.Open)
label1.Text = "Nope!!";
string sql = "SELECT * FROM Main";
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, myConnection);
DataSet myDataSet = new DataSet("Main");
myAdapter.Fill(myDataSet, "Main");
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.Refresh();
}
You need to call after setting the DataSource
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = myDataSet.DefaultViewManager;
dataGridView1.DataBind();
EDIT
dataGridView1.DataSource = myDataSet.Tables[0];
dataGridView1.AutoGenerateColumns = true;
How about this?
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 Excel = Microsoft.Office.Interop.Excel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
private DataTable table;
private DAL dal;
protected void Form_Load(object sender, EventArgs e)
{
dal = new DAL();
table = dal.GetData();
dataGridView1.DataSource = table;
}
public Form1()
{
InitializeComponent();
}
private void button5_Click(object sender, EventArgs e)
{
dal.UpdateData(table);
}
class DAL //data access layer
{
string connString = #"Server=EXCEL-PC\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
SqlDataAdapter da;
SqlCommandBuilder builder;
DataTable table;
SqlConnection conn;
public DataTable GetData()
{
table = new DataTable("dataGridView1");
conn = new SqlConnection(connString);
da = new SqlDataAdapter();
da.SelectCommand = new SqlCommand(#"SELECT * FROM [SalesLT].[Product]", conn);
builder = new SqlCommandBuilder(da);
da.Fill(table);
return table;
}
public void UpdateData(DataTable table)
{
if (da != null && builder != null)
{
da.Update(table);
}
}
}
}
}
Here is another option for you to consider.
private void button6_Click(object sender, EventArgs e)
{
SqlConnection con = new System.Data.SqlClient.SqlConnection();
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Server=EXCEL-PC\\EXCELDEVELOPER;Database=AdventureWorksLT2012;Trusted_Connection=True;";
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
for (int i = 0; i <= dataGridView1.Rows.Count - 2; i++)
{
String insertData = "INSERT INTO Import_List(Fname, Lname, Age) VALUES (#Fname, #Lname, #Age)";
SqlCommand cmd = new SqlCommand(insertData, con);
cmd.Parameters.AddWithValue("#Fname", dataGridView1.Rows[i].Cells[0].Value);
cmd.Parameters.AddWithValue("#Lname", dataGridView1.Rows[i].Cells[1].Value);
cmd.Parameters.AddWithValue("#Age", dataGridView1.Rows[i].Cells[2].Value);
da.InsertCommand = cmd;
cmd.ExecuteNonQuery();
}
con.Close();
}
I'm trying to writing a basic c# program that read datas from SQL and writes results on 3 textboxes and a label. Here is my code;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace PLAKA
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=TESTDB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Project where ID = '" + textBox1.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
textBox1.Text = dt.Rows[0][0].ToString();
textBox2.Text = dt.Rows[0][1].ToString();
textBox3.Text = dt.Rows[0][2].ToString();
textBox4.Text = dt.Rows[0][3].ToString();
SqlDataAdapter oks = new SqlDataAdapter("SELECT * FROM Project where Status = 'YES'", con);
if (oks)
{
label1.Text = "POSITIVE";
}
else
{
label1.Text = "NEGATIVE";
}
}
}
}
I'm writing ID number and see the informations of this ID on text boxes in my first part of my code and this works perfectly
All i need that when value in the 'Status' raw is "YES", my program writes "POSITIVE", other else writes 'NEGATIVE' on label1
Meanwhile Status information writes on Textbox3.
For this code i got this error message: "Error 1 Cannot implicitly convert type 'System.Data.SqlClient.SqlDataAdapter' to 'bool'
How can i solve this problem?
Your If condition is wrong.
use this.
SqlDataAdapter oks = new SqlDataAdapter("SELECT * FROM Project where Status = 'YES'", con);
oks.fill(dataSet)
if (dataSet.Tables["Table"].Rows.Count > 1)
{
label1.Text = "POSITIVE";
}
else
{
label1.Text = "NEGATIVE";
}
I'm a beginner in c#.net. I'm having problem in binding the database (mysql) to datagridview. The error shows that my query is wrong. I pretty sure the query was right as I tested it on MySQL script. And I try to show it in datagridview by the way. dbMetName is datagridview. Here is my code
private void Binding()
{
string connStr = "datasource=localhost;port=3306;username=root;password=root;";
conn = new MySqlConnection(connStr);
MySqlCommand command = conn.CreateCommand();
try
{
string database = schemaForm.getData;
dtable = new DataTable();
bindingSource = new BindingSource(); ;
conn.Open();
command.CommandText = "SELECT Metabolite_Name" +
"FROM " + database +
".Metabolites WHERE"+
" MetaboliteID IN ('met1', 'met2');";
command.ExecuteNonQuery();
sqlData.SelectCommand = command;
sqlData.Fill(dtable);
bindingSource.DataSource = dtable;
dbMetName.DataSource = dtable;
dtable.Columns.Add("Metabolite Name");
dbMetName.DataSource = dtable;
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Passing value from getData form
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;
namespace DynamicSimulator_v2
{
public partial class SchemaName : Form
{
private static string data;
public SchemaName()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Hide();
}
private void btnOK_Click(object sender, EventArgs e)
{
data=txtDB.Text;
this.Hide();
}
public string getData
{
set
{
data = txtDB.Text;
}
get
{
return data;
}
}
}
}
There's a missing space between Metabolite_Name and FROM:
"SELECT Metabolite_Name" +
"FROM " + database +
ExecuteNonQuery returns nothing but the number of affected lines. Try this:
public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
I am currently building an application in C#. In this application, people give values in a label and that values will be saved in a database. This also works at the moment. What I want is the following:
The people can see their own values back in a datagridview. If I do this with the wizard of the datagridview I can't select label2.Text(this is the customerID).
The query I used below is the following:
SELECT * FROM prestaties WHERE gebruikerid = '" + label1.Text + "'";
But it doesn't work. I don't see anything in my datagrid.
Sorry for my bad English. I hope you can understand me.
The code below I already have, but it doesn't work
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;
namespace Eindopdracht
{
public partial class resultaten : Form
{
public resultaten()
{
InitializeComponent();
dataGridView1.Show();
}
private string username;
public void displaydata(String ddata)
{
OleDbConnection conn = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string select = "SELECT * FROM prestaties WHERE gebruikerid = '" + label2.Text + "'";
conn.Open();
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(select, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds);
dataGridView1.DataSource = ds.tables[0];
conn.Close();
}
public void setUsername(String name)
{
username = name;
label1.Text = username;
setID();
}
public void setID()
{
OleDbConnection vcon = new OleDbConnection(#"provider= microsoft.jet.oledb.4.0;data source=C:\\Users\\Jeffrey\\Desktop\\Eindopdracht WOE\\Eindopdracht\\sample.mdb");
string selectie = "SELECT id FROM inlog WHERE Username='" + label1.Text + "'";
OleDbCommand vcom1 = new OleDbCommand(selectie, vcon);
vcon.Open();
vcom1.ExecuteNonQuery();
OleDbDataReader dr = null;
dr = vcom1.ExecuteReader();
while (dr.Read())
{
var waarde = dr.GetValue(0);
label2.Text = waarde.ToString();
}
I don't know if my code is 100% correct. I've build this by myself. If I use the class displayData in the begin next to InitializeComponent(); I will get an error.