C# How to sort combobox items by date - c#

void Fillcombo()
{
cbxProducts.Text = "";
cbxProducts.Items.Clear();
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
What the database looks like
I can't figure out how to sort the items listed in the combobox by their date while just displaying their Name

void Fillcombo()
{
cbxProducts.Text = "";
cbxProducts.Items.Clear();
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products ORDER BY EDate;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
cbxProducts.Sorted = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This fixed it for me

Sort the dates before adding them to the combobox. Using "ORDER BY", the content is sorted by the String representation.
Make sure to turn of auto sorting.
Source

public class YourObject : IComparable{
public YourObject(string name) {
Name = name;
}
public string Name { get; set; }
public override string ToString()
{
return GetHashCode().ToString() + "_" + Name;
}
#region IComparable Members
public int CompareTo(Object other)
{
return Comparer.Default.Compare(this.ToString(), other.ToString());
}
#endregion
}

Related

SQL command returning null for value

I am previously only familiar with Linq and the like for data access. I am working on something now that requires me to use actual SQL commands on the back end to return a single value. My code compiles and runs, however it is returning null for a value that I know should be returning something besides an empty string...
Is my structure off on this? Or is something else missing?
Below is my code:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
Here is a picture of the result set of the table:
Open the connection.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open(); //<- This line here.
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
cmd.ExecuteScalar() is probably throwing an InvalidOperationException because you haven't opened the connection. The exception is being caught, outputted to the console, then the initial value of newSex is begin returned since the call to ExecuteScalar threw.
ID is a int or varchar?
If is int use:
cmd.Parameters.Add("#sex", SqlDbType.Int).Value = sex;
instead of:
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
P.S.
Query parameters and parameter add into cmd.Parameters is case sensitive.
Write
#sex
instead of
#Sex
Figured it out. Had to open the cmd and close it AFTER I set the newSex variable to the value being pulled.
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID = #Sex";
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
cmd.Connection = conn;
adapter.SelectCommand = cmd;
cmd.Parameters.Add("#Sex", SqlDbType.VarChar).Value = sex;
adapter.Fill(ds);
newSex = cmd.ExecuteScalar().ToString();
conn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}
}
Try this:
internal string GetSexDescription(string sex, int id_merchant)
{
string newSex = "";
var builder = new ConnectionStringHelper();
var connString = builder.getCasinoDBString(id_merchant);
using (SqlConnection conn = new SqlConnection(connString))
{
string sql = "SELECT Description FROM person_gender_lookup WHERE ID" + sex;;
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
newSex = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return newSex;
}
}

SQL contact application not responding with server correctly

I have just finished making a contact application, where basically you input the contacts details and it will save it to a SQL database.
I am very sorry if my code is confusing everyone because I am a big noobie at coding.
Connection String
<add name="connstrng" connectionString="Data Source=DESKTOP-MJ61J7L\SQLEXPRESS;Initial Catalog=Econtact;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"/>
C#
class contactClass
{
//getter and setter properties
//acts as data carrier in our application
public int ContactID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ContactNo { get; set; }
public string Address { get; set; }
public string Gender { get; set; }
static string myconnstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
//selecting data from database
public DataTable Select() {
//Database Connection
SqlConnection conn = new SqlConnection(myconnstrng);
DataTable dt = new DataTable();
try
{
//Writing sql query
string sql = "SELECT * FROM tbl_contact";
//creating cmd using sql and conn
SqlCommand cmd = new SqlCommand(sql, conn);
//creating sql dataAdapter using cmd
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
conn.Open();
adapter.Fill(dt);
} catch(Exception e)
{
} finally
{
conn.Close();
}
return dt;
}
//inserting data into DataBase
public bool Insert (contactClass c)
{
//creating a default return type and setting its value to false
bool isSuccess = false;
//Connect to DataBase
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_contact (FirstName, LastName, ContactNo, Address, Gender) VALUES (#FirstName, #LastName, #ContactNo, #Address, #Gender) ";
//creating cmd using sql and conn
SqlCommand cmd = new SqlCommand(sql, conn);
//Inserting Parameters into tbl_contact
cmd.Parameters.AddWithValue("#FirstName", c.FirstName);
cmd.Parameters.AddWithValue("#LastName", c.LastName);
cmd.Parameters.AddWithValue("#ContactNo", c.ContactNo);
cmd.Parameters.AddWithValue("#Addresss", c.Address);
cmd.Parameters.AddWithValue("#Gender", c.Gender);
conn.Open();
int row = cmd.ExecuteNonQuery();
//if the query runs successfully then the value of the rows will be != 0 (because the default it 0)
if(row > 0)
{
isSuccess = true;
} else
{
isSuccess = false;
}
} catch(Exception e)
{
} finally
{
conn.Close();
}
return isSuccess;
}
//method to update data in our database from our application
public bool Update(contactClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "UPDATE tbl_contact SET FirstName=#FirstName, LastName=#LastName, ContactNo=#ContactNo, Address=#Address, Gender=#Gender WHERE ContactID=#ContactID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#FirstName", c.FirstName);
cmd.Parameters.AddWithValue("#LastName", c.LastName);
cmd.Parameters.AddWithValue("#ContactNo", c.ContactNo);
cmd.Parameters.AddWithValue("#Addresss", c.Address);
cmd.Parameters.AddWithValue("#Gender", c.Gender);
//open database connection
conn.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception e)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
//method to delete data from our database
public static bool Delete(contactClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
//sql to delete data
string sql = "DELETE FROM tbl_contact WHERE ContactID=#ContactID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ContactID", c.ContactID);
//open sql connection
conn.Open();
int rows = cmd.ExecuteNonQuery();
//runs the isSuccess variable if statement
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch(Exception e)
{
}
finally
{
//Close sql connection
conn.Close();
}
return isSuccess;
}
}
Add Button
private void btnAdd_Click(object sender, EventArgs e)
{
//Get the value from the input fields
c.FirstName = txtboxFirstName.Text;
c.LastName = txtboxLastName.Text;
c.ContactNo = txtboxPhonenumber.Text;
c.Address = txtboxAddress.Text;
c.Gender = cmbGender.Text;
c.FirstName = txtboxFirstName.Text;
//inserting data into the database using the method we created in the last video
bool success = c.Insert(c);
if (success == true)
{
MessageBox.Show("New contact successfully created.");
}
else
{
MessageBox.Show("Failed to add contact. Try Agian.");
}
}
I do think that it might be due to the connection to my data base....
I Also got this message in my output-
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Idk if this means anything though.
#mjwills Addresss is misspelled (twice). That would explain what you are seeing.
Thanks man, uhgg so obvious. I really appreciate it I would never have found that.

How to Remove Duplicate OUTPUT in SQL?

I have a problem with a ComboBox, its items are being duplicated. How can I prevent this situation? Here is some images:
Here is my code sample used to populate it:
string SelectQuery = "SELECT Part , Model FROM ctautoparts.nissanpart , ctautoparts.nissan ;";
MySqlConnection sqlConn = new MySqlConnection(myConnectionString);
MySqlCommand cmdDatabase = new MySqlCommand(SelectQuery, sqlConn);
MySqlDataReader myReader;
try
{
sqlConn.Open();
myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
// string namethestore = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("model");
// this.carmodel.Text = namethestore;
// string namethestore1 = myReader.IsDBNull(model)
// ? string.Empty
// : myReader.GetString("parts");
/// this.carpart.Text = namethestore1;
carmodel.Items.Add(myReader["Model"].ToString());
carpart.Items.Add(myReader["Part"].ToString());
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}
Add distinct to your select query, so that the duplicates will be removed
It looks your query is returning duplicated lines. I'd suggest executing them separatedely:
try
{
// POPULATE MODELS
string modelsQuery = "SELECT Model FROM ctautoparts.nissan;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(modelsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carmodel.Items.Add(myReader["Model"].ToString());
}
}
}
// POPULATE PARTS
string partsQuery = "SELECT Part FROM ctautoparts.nissanpart;";
using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmdDatabase = new MySqlCommand(partsQuery, sqlConn))
{
sqlConn.Open();
MySqlDataReader myReader = cmdDatabase.ExecuteReader();
// int model = myReader.GetOrdinal("model");
//int model1 = myReader.GetOrdinal("part");
while (myReader.Read())
{
carpart.Items.Add(myReader["Part"].ToString());
}
}
}
}
catch (Exception msg)
{
MessageBox.Show(msg.Message);
}

c# Auto populate result of a textboxt.Text from database, base on 2 different combo box

namespace Training
{
public partial class AddingNewData : Form
{
public AddingNewData()
{
InitializeComponent();
fillcombo1();
fillcombo2();
autopopulatedays();
}
string original_city, destination_city;
void fillcombo1()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT * FROM itemdelivery.fee GROUP BY orig_city;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string storig = myReader.GetString("orig_city");
comboBox1.Items.Add(storig);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void fillcombo2()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT * FROM itemdelivery.fee GROUP BY dest_city;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string stdest = myReader.GetString("dest_city");
comboBox2.Items.Add(stdest);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
original_city = comboBox1.Text;
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
destination_city = comboBox2.Text;
}
private void txt_deliverytime_TextChanged(object sender, EventArgs e)
{
}
void autopopulatedays()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT `del_time` FROM `itemdelivery.fee` WHERE `orig_city` = #oc AND `dest_city`= #dc";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
try
{
conDataBase.Open();
cmdDataBase.Parameters.AddWithValue("#oc", original_city);
cmdDataBase.Parameters.AddWithValue("#dc", destination_city);
object result = cmdDataBase.ExecuteScalar();
if (result != null)
txt_deliverytime.Text = result.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
So, I have 2 combo boxes, After selecting 2 of them, I put the values in original_city and destination_city as string, using comboBox1_SelectedIndexChanged and comboBox2_SelectedIndexChanged.
Then on method autopopulatedays(), I tried to auto-populate the txt_deliverytime.Text with a single integer value by matching the value of original_city and destination_city on the database using
that query.
But, so why I failed? The only error I got is "No database selected" which is weird for me, and when I select 2 combo box choices, the
txt_deliverytime.Text doesn't get auto-populated.
========================================================================
// UPDATE VERSION
// Connected to database, and ignoring the code before(above),
// This code only meant to auto-populate txt_deliverytime.Text when
// combobox1.selectitem and combobox2.selectitem
// Why it's still wrong?.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
original_city = comboBox1.SelectedItem.ToString();
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
destination_city = comboBox2.SelectedItem.ToString();
// if the combobox1 is not empty and combobox2 is also not empty, then run this code
if (comboBox1.SelectedItem.ToString() != null)
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT del_time FROM itemdelivery.fee WHERE orig_city='" + original_city + "' AND dest_city='" + destination_city + "';";
// if I run this query on MySQL, it will show only a column name del_time with only a single row,
// thus only show a value, I want to get that value to txt_deliverytime.Text
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
conDataBase.Open();
string getValue = cmdDataBase.ExecuteScalar().ToString();
if (getValue != null)
{
txt_deliverytime.Text = getValue.ToString();
// meant to change it here, but seems not successful
}
conDataBase.Close();
}
}
First use a valid ConnectionString:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;
Pwd=myPassword;
Then I suppose this is not your actual code, because there is a missing curly bracket
public partial class AddingNewData : Form
{
public AddingNewData()
{
InitializeComponent();
fillcombo1();
fillcombo2();
autopopulatedays();
}
And finally you should `autopopulatedays' when comboBox1 or comboBox2 selected item change, not only when you fill the combos.
I solved the code above into the code like this below =
namespace Training
{
public partial class AddingNewData : Form
{
public AddingNewData()
{
InitializeComponent();
fillcombo1();
fillcombo2();
}
string original_city, destination_city;
void fillcombo1()
{
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT * FROM itemdelivery.fee GROUP BY orig_city;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string storig = myReader.GetString("orig_city");
comboBox1.Items.Add(storig);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void fillcombo2()
{
// EMPTY
}
// just some improvement on query
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
original_city = comboBox1.SelectedItem.ToString();
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT DISTINCT dest_city FROM itemdelivery.fee WHERE orig_city = '" + original_city + "' GROUP BY destination_city ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string stdest = myReader.GetString("dest_city");
comboBox2.Items.Add(stdest);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// this is where I solved the problem
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
destination_city = comboBox2.SelectedItem.ToString();
string constring = "datasource=localhost;port=3306;username=root;password=root";
string Query = "SELECT del_time FROM itemdelivery.fee WHERE orig_city ='" + original_city + "' AND dest_city ='" + destination_city + "';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
try
{
conDataBase.Open();
var result = cmdDataBase.ExecuteScalar();
if (result != null)
{
txt_deliverytime.Text = result.ToString();
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void txt_deliverytime_TextChanged(object sender, EventArgs e)
{
}
}

unable to cast object of type system.int32 to type system.string combobox fill from database

I get the 'unable to cast object of type system.int32 to type system.string' error message when I try to populate a combobox from a datatable. The data is an int type (used as an identity column) the class is called on form load.
void fillComboRef()
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "select * from customersTBL ";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sRef = myReader.GetString(myReader.GetOrdinal("Reference"));
comboRef.Items.Add(sRef);
}
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Try:
int ordinal = myReader.GetOrdinal("Reference");
int reference = myReader.GetInt32(ordinal);
string sRef = reference.ToString();
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "select Reference from customersTBL ";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
comboRef.Items.Add(Convert.ToString(myReader.GetInt32(0)));
//string sRef = Convert.ToString(myReader.GetString(myReader.GetOrdinal("Reference")));
// comboRef.Items.Add(sRef);
}
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Categories

Resources