Greetings i am facing this problem where i need to remove any duplicates that are being populated from mysql database into the combobox.
this is my code:
void fillcatagory()
{
string query = "select * from CatagorieTable";
MySqlCommand cmd = new MySqlCommand(query, Con);
MySqlDataReader rdr;
try
{
Con.Open();
DataTable dt = new DataTable();
dt.Columns.Add("Catagname", typeof(string));
rdr = cmd.ExecuteReader();
dt.Load(rdr);
catcombo.ValueMember = "Catagname";
catcombo.DataSource = dt;
searchcombo.ValueMember = "Catagname";
searchcombo.DataSource = dt;
Con.Close();
}
catch
{
}
}
Update your query to return unique category names like so:
string query = "select distinct Catagname from CatagorieTable";
Since you're only using the one column, there's no reason to select anything else.
Related
I'm trying to insert some records to 2 tables at same event
private void Btngravar_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("server=localhost;user id=root;database=saude;Password=");
conn.Open();
MySqlCommand objcmd = new MySqlCommand("insert into dispensacao (DESTINATARIO,COD_UNIDADE,COD_DEPARTAMENTO,DATA,SOLICITANTE,DEFERIDO_POR) values(?,?,?,?,?,?)", conn);
objcmd.Parameters.Add("#DESTINATARIO", MySqlDbType.VarChar, 45).Value = Cmbdestinatario.Text;
objcmd.Parameters.AddWithValue("#COD_UNIDADE", string.IsNullOrEmpty(Txtcodigounidade.Text) ? (object)DBNull.Value : Txtcodigounidade.Text);
objcmd.Parameters.AddWithValue("#COD_DEPARTAMENTO", string.IsNullOrEmpty(Txtcodigodep.Text) ? (object)DBNull.Value : Txtcodigodep.Text);
DateTime fdate = DateTime.Parse(Txtdata.Text);
objcmd.Parameters.Add("#DATA", MySqlDbType.DateTime).Value = fdate;
objcmd.Parameters.Add("#SOLICITANTE", MySqlDbType.VarChar, 45).Value = Txtsolicitante.Text;
objcmd.Parameters.Add("#DEFERIDO_POR", MySqlDbType.VarChar, 45).Value = Txtdeferido.Text;
objcmd.ExecuteNonQuery();
conn.Close();
conn.Open();
objcmd = new MySqlCommand("insert into produtos_disp(COD_DISPENSACAO,COD_PRODUTO,PRODUTO,QUANTIDADE) values (?,?,?,?)", conn);
string selectid = "select ifnull (max(ID),1) from dispensacao";
objcmd = new MySqlCommand(selectid, conn);
MySqlDataReader reader = objcmd.ExecuteReader();
if (reader.Read())
{
Txtcodigo.Text = reader.GetString("ID");
}
//Txtcodigo.DataBindings.Add("Text", dtid, "ID");
objcmd.Parameters.AddWithValue("#COD_DISPENSACAO", Txtcodigo.Text);
objcmd.Parameters.AddWithValue("#COD_PRODUTO", dtproddisp.Rows[0][0]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][1]);
objcmd.Parameters.AddWithValue("#PRODUTO", dtproddisp.Rows[0][2]);
Code from the comment
string selectQuery = "SELECT * from departamento";
connection.Open();
MySqlCommand command = new MySqlCommand(selectQuery, connection);
MySqlDataReader reader = command.ExecuteReader();
DataTable dt2 = new DataTable();
dt2.Load(reader);
Cmbdestinatario.DisplayMember = "nome";
Cmbdestinatario.ValueMember = "CODIGO";
Cmbdestinatario.DataSource = dt2;
Txtcodigodep.DataBindings.Add("Text", dt2, "CODIGO");
The first part is working, I can see records inserted on dispensacao table, but the second isn't working, error:
Could not find specified column in results: ID
and I need to get products from datagridview,
App screen:
MySQL Dispensacao table:
My problem now is inserting those selected products from datagridview on database and get the id from dispensacao to insert on products table,
If you want to insert more rows in a database(from what I known), you should add a checkbox in a DataGridView Column and store checked rows to a list. Then you should use a for loop to insert each data to Database by list values.
If you want the code please comment me.
This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("price");
dt.Columns.Add("image");
dt.Columns.Add("cost");
dt.Columns.Add("totalcost");
if (Request.QueryString["item_name"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
Change
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
to be:
String myquery = "select * from food_items where item_name=#item_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);
Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.
Using parameters like above will help avert the majority of problems you will encounter.
I would like to eliminate duplicates from OleDbDataReader
Should be easy but I'm spinning my wheels. Any help would be appreciated!
private void Database_Load(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from PPAPdatabase";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox_Owner.Items.Add(reader["Owner"].ToString());
}
Refactor your SQL query like this :
select distinct Owner from PPAPdatabase
Instead of
select * from PPAPdatabase
The only column you need in your code is Owner then get that only one column and apply DISTINCT clause to it to get distinct value for that column.
Or replace the following lines :
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
comboBox_Owner.Items.Add(reader["Owner"].ToString());
}
By this :
var owners = dt.AsEnumerable().Select(row => row["Owner"].ToString()).Distinct();
foreach(var owner in owners)
{
comboBox_Owner.Items.Add(owner);
}
In this solution we're using one SQL Query to your Database and reuse the result to extreact distinct owners.
you can do this way
while (reader.Read())
{
if (!comboBox_Owner.Items.Contains(reader["Owner"].ToString()))
comboBox_Owner.Items.Add(reader["Owner"].ToString());
}
I wrote SQLite wrapper class
like this
using System;
using System.Data;
using System.Data.SQLite;
namespace SuPOS.Sources
{
public class SQLITE
{
private SQLiteConnection con;
private SQLiteCommand cmd;
private SQLiteDataAdapter adapter;
public SQLITE(string databasename)
{
con = new SQLiteConnection(string.Format("Data Source={0};Compress=True;", databasename));
}
public int Execute(string sql_statement)
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = sql_statement;
int row_updated;
try
{
row_updated = cmd.ExecuteNonQuery();
}
catch
{
con.Close();
return 0;
}
con.Close();
return row_updated;
}
public DataTable GetDataTable(string tablename)
{
DataTable DT = new DataTable();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", tablename);
adapter = new SQLiteDataAdapter(cmd);
adapter.AcceptChangesDuringFill = false;
adapter.Fill(DT);
con.Close();
DT.TableName = tablename;
return DT;
}
public void SaveDataTable(DataTable DT)
{
try
{
Execute(string.Format("DELETE FROM {0}", DT.TableName));
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", DT.TableName);
adapter = new SQLiteDataAdapter(cmd);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(DT);
con.Close();
}
catch (Exception Ex)
{
System.Windows.MessageBox.Show(Ex.Message);
}
}
}
}
I retrive DataTable from Database by "GetDataTable"
and binding to control.itemsource in WPF such as DataGrid
I can add new row on DataGrid and save to Database properly
I can change any column and save to database properly
but the problem is,
when I insert new row to DataGrid and call "SaveDataTable" as usual
I can save properly.. then I change some column on that row
now when I use "SaveDataTable" it said like this picture
after this message appear,
when I call "SaveDataTable" it will always said like this picture
I know this is an old thread, but the extra code you wrote for your solution only works because it cancels out a bug in your code, where you set:
adapter.AcceptChangesDuringFill = false ; /* default is 'true' */
If you remove the above line, you no longer need to have the row accept the changes and your method becomes much cleaner:
public DataTable GetDataTable(string tablename)
{
DataTable DT = new DataTable();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", tablename);
adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(DT);
con.Close();
DT.TableName = tablename;
return DT;
}
finally, I found the solution.
the problem came from rowstate of each row after I call Fill(DataTable), every DataRow in DataTable after Fill have "Added" in RowState.
so I can't call "Update(DataTable)" because it will Insert every rows in DataTable to Database.
because of that, in my wrapper class I have to Delete all rows in Database before "Update(DataTable).
so, I have to change RowState in every DataRow after method Fill(DataTable) by "AcceptChanges" method.
public DataTable GetDataTable(string tablename)
{
DataTable DT = new DataTable();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", tablename);
adapter = new SQLiteDataAdapter(cmd);
adapter.AcceptChangesDuringFill = false;
adapter.Fill(DT);
con.Close();
DT.TableName = tablename;
foreach (DataRow row in DT.Rows)
{
row.AcceptChanges();
}
return DT;
}
public void SaveDataTable(DataTable DT)
{
try
{
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = string.Format("SELECT * FROM {0}", DT.TableName);
adapter = new SQLiteDataAdapter(cmd);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);
adapter.Update(DT);
con.Close();
}
catch (Exception Ex)
{
System.Windows.MessageBox.Show(Ex.Message);
}
}
Now I don't have to Delete all row before Update, and the problem gone.
I want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..