C# How to eliminate duplicate values from comboBox? - c#

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());
}

Related

Eliminating Duplicates from combobox C#

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.

Integer is being returned as 0 when it shouldn't be. Retrieved from database

I'm trying to get a value from my database but it keeps returning a value of 0 and i cannot figure out why. I've been retrieving data from the database for the whole of my project and it is just not working here. None of the values in the database are = to 0.
int rentalPrice is the one being returned as 0`
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] == null)
{
Response.Redirect("DisplayCars.aspx");
}
else
{
id = Convert.ToInt32(Request.QueryString["id"].ToString());
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from cars where id ='" + id + "'";
cmd.ExecuteNonQuery();
lblCarID.Text = id.ToString();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd);
foreach (DataRow dr2 in dt2.Rows)
{
rentalPrice = Convert.ToInt32(dr2["car_rental_price"]);
}
lblRentalPrice.Text = rentalPrice.ToString();
con.Close();
}
// This uses a Connection pool, so you don't need to reuse the same SqlConnection
using (SqlConnection con = new SqlConnection(...))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select [car_rental_price] from cars where id = #Id";
var idParam = new SqlParameter("#Id");
idParam.Value = id;
cmd.Parameters.Add(idParam);
con.Open();
using (var reader = cmd.ExcecuteReader())
{
reader.Read();
lblRentalPrice.Text = reader.GetInt32(0).ToString();
lblCarID.Text = id.ToString();}
}
}
}
To execute a query and get results, you need to use cmd.ExecuteReader.
Also, rather than concatenating values into a string to build your SQL query, you need to use parameterized queries. This helps prevent SQL Injection attacks.
Also, SqlConnection should not be put in a field (class level variable). Instead, you should use local variables and wrap them in a using statement to ensure that they get disposed of properly.
hey you did not fill the Data Table.. then how it has any Values???
first Fill the data Table and use it in Foreach loop
adapter.Fill(DataTable);
foreach(DataRow dr in DataTable)
{
//get the id
}

How to add items to a comboBox in C# from two tables?

I'd really appreciate if someone could help me figure out how to fill two comboboxes data from two different tables. The code below doesn't seem to be working for me.
string command = "SELECT * FROM [Course]";
string command2 = "SELECT * FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
SqlDataReader reader2 = db.commandExecute(command2);
while (reader.Read())
{
comboBox2.Items.Add(reader["CourseID"].ToString());
}
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
reader.Close();
reader2.Close();
db.connectionEnd();
Instead of using two queries you can try like this
string command = "SELECT * FROM [Course] UNION ALL SELECT * FROM [Module]";
If you have columns mismatch problem while joining query use NULL as Column1 for extra column
Eg-:
string command = "SELECT CUSTID AS ID FROM [Course] UNION ALL SELECT ModuleID AS ID FROM [Module]";
dbConnection db = new dbConnection();
SqlDataReader reader = db.commandExecute(command);
while (reader.Read())
{
comboBox2.Items.Add(reader["ID"].ToString());
}
reader.Close();
db.connectionEnd();
Update
I thought that you are going to add two table values in same comboxbox that's why posted above code.
Can you try this code it worked for me
SqlConnection con = new SqlConnection("Data Source=pcname;Initial Catalog=database;Persist Security Info=True;User ID=sa;Password=123");
SqlCommand cmd = new SqlCommand("SELECT * FROM [Course]", con);
SqlCommand cmd1 = new SqlCommand("SELECT * FROM [Module]", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
ComboBox1.Items.Add(dr(0).ToString);
}
}
dr.Close();
SqlDataReader dr1 = cmd1.ExecuteReader;
if (dr1.HasRows)
{
while (dr1.Read)
{
ComboBox2.Items.Add(dr1(0).ToString);
}
}
dr1.close();
con.close();
Hope this help you
Change your code
while (reader2.Read())
{
comboBox1.Items.Add(reader["ModuleID"].ToString());
}
with
while (reader2.Read())
{
// Change here the name of reader
comboBox1.Items.Add(reader2["ModuleID"].ToString());
}

How to populate data from SQL Server database columns to textboxes

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..

c# - Do you need a DataTable to retrieve data from a DataAdapter?

Most of my queries are very short, 1-3 records total. This is the code I have now. I am wondering if there is a way to capture userid directly from DataAdapter without going through a table. Thanks!
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable t = new DataTable();
dataAdapter.Fill(t);
int userid = 0;
if (t.Rows.Count > 0)
{
DataRow dr = t.Rows[0];
userid = dr.Field<int>(0);
If you have only one return value, you can use ExecuteScalar and you have ExecuteReader to get multiple return values.
Here's the msdn sample:
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
}
Use a reader:
http://msdn.microsoft.com/en-US/library/system.data.sqlclient.sqldatareader(v=vs.80).aspx
Quicker and less resources 1 record or hundreds.

Categories