how to sort listbox using comboboxC# - c#

I want to sort my listbox using combobox,
the combobox will include A-Z and Z-A , so how can I do it and let it work ?
some of my code for the listbox ,lst_OrderName is the one i want to sort.
private void AllorderBySearch()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter adapter = new SqlDataAdapter("select* from Tbl_order WHERE CustomerNo = '" + txt_CustomerNo.Text + "' And OrderName LIKE '%" + txt_OrderNo.Text + "%' AND OrderName LIKE '%" + txt_OrderNo.Text + "%' AND OrderName LIKE '%" + txt_OrderNo.Text + "%' AND Date between '" + dateTimePicker1.Text + " 00:00:00.000' AND '" + dateTimePicker1.Text + " 23:59:59.999'; ", connection))
{
DataTable Tbl_order = new DataTable();
connection.Open(); //opens the connection
adapter.Fill(Tbl_order);
connection.Close(); //Closes the connection
lst_CustomerNo.DataSource = Tbl_order; //assigns a datasource
lst_CustomerNo.DisplayMember = "CustomerNo"; //assigns display
lst_CustomerNo.ValueMember = "CustomerNo";
lst_OrderName.DataSource = Tbl_order;
lst_OrderName.DisplayMember = "OrderName";
lst_OrderName.ValueMember = "OrderName";
lst_Quantity.DataSource = Tbl_order;
lst_Quantity.DisplayMember = "Quantity";
lst_Quantity.ValueMember = "Quantity";
lst_Price.DataSource = Tbl_order;
lst_Price.DisplayMember = "Price";
lst_Price.ValueMember = "Price";
lst_datetime.DataSource = Tbl_order;
lst_datetime.DisplayMember = "Date";
lst_datetime.ValueMember = "Date";
}
}
I created combobox but i didn't do anything in it yet cuse I dunno how to make it by the way i want . could you help me plz?

you must use a temp object for sorting like bubble sort

As you are using a DataTable as the data source, the following should work:
private void cmbSort_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = lst_CustomerNo.DataSource as DataTable;
if(cmbSort.SelectedItem == "A-Z")
dt.DefaultView.Sort = "OrderName ASC";
else
dt.DefaultView.Sort = "OrderName DESC";
}
Attach the above event to your combobox SelectedIndexChanged action..

Related

c# search datagridview with numbers [duplicate]

I have a form that when I select a column name from a ComboBox, and type in a text box it filters and displays the searched criteria in the DataGridView. When I search for "Reference" which is an int data type, which is also identity, and primary key. I get the error message :
"Cannot perform 'Like' operation on System.Int32 and System.String."
My code is
DataTable dt;
private void searchForm_Load(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=|DataDirectory|\LWADataBase.sdf;");
SqlCeDataAdapter sda = new SqlCeDataAdapter("select * from customersTBL", con);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
comboSearch.Items.Add("[Reference]");
comboSearch.Items.Add("[First Name]");
comboSearch.Items.Add("[Surename]");
comboSearch.Items.Add("[Address Line 1]");
comboSearch.Items.Add("[Address Line 2]");
comboSearch.Items.Add("[County]");
comboSearch.Items.Add("[Post Code]");
comboSearch.Items.Add("[Contact Number]");
comboSearch.Items.Add("[Email Address]");
}
private void searchTxt_TextChanged(object sender, EventArgs e)
{
if (comboSearch.SelectedItem == null)
{
searchTxt.ReadOnly = true;
MessageBox.Show("Please select a search criteria");
}
else
{
searchTxt.ReadOnly = false;
DataView dv = new DataView(dt);
dv.RowFilter = "" + comboSearch.Text.Trim() + "like '%" + searchTxt.Text.Trim() + "%'";
dataGridView1.DataSource = dv;
}
}
Convert the number to a string inside the filter:
dv.RowFilter = string.Format("CONVERT({0}, System.String) like '%{1}%'",
comboSearch.Text.Trim(), searchTxt.Text.Trim());
Try this perhaps?
dv.RowFilter = "'%" + comboSearch.Text.Trim() + "%' like '%" + searchTxt.Text.Trim() + "%'";
It may just be a missing quotation, because the query reads as
" 123 like '%123%' "
the code tried to search from gridview (devexpress)..
DataRow[] dr = dt.Select("invoiceId ='" + Convert.ToInt32(gridView1.GetRowCellValue(id, "invoiceId")) + "' AND '%" + Convert.ToDouble(gridView1.GetRowCellValue(id, "Amount_Paid")) + "%' LIKE '%" + Convert.ToDouble(gridView1.GetRowCellValue(id, "Amount")) + "%' ");
if (dr.Length > 0)
{
MessageBox.Show("already paid");
}

How to add value of column A if it exist on Table 2 using Datagridview

Mabuhay!
What is the most efficient or more convenient way to do this.
I have a select query and put it on a datagridview base on my filter. It has 5 columns. I want to know if Column CA from that Datagridview already exist on Table 2 which is on Column 3?
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=db;User ID=sa;Password=pw");
// DateTime dt = new DateTime();
//dt = DateTime.Now.ToString();
SqlDataAdapter sda = new SqlDataAdapter("SELECT max(PurchaseOrder.POTitle) as Description,sum(PurchaseOrderEntry.Price *PurchaseOrderEntry.QuantityOrdered) as Amount, max(PurchaseOrder.PONumber)as PONumber, " +
" max(PurchaseOrderEntry.OrderNumber) as BoxCount, max(PurchaseOrderEntry.OrderNumber) as PLC,max(PurchaseOrderEntry.OrderNumber) as Branch, max(PurchaseOrderEntry.OrderNumber) as PreparedBy, max(PurchaseOrderEntry.OrderNumber) as CheckedBy " +
" FROM PurchaseOrder LEFT OUTER JOIN" +
" PurchaseOrderEntry ON PurchaseOrder.ID = PurchaseOrderEntry.PurchaseOrderID" +
" WHERE (PurchaseOrder.Remarks like '%" + tanggapan.Text + "%') AND (PurchaseOrder.DateCreated BETWEEN '" + dateTimePicker1.Text + "' AND '" + dateTimePicker2.Text + "' and PurchaseOrder.OtherStoreID = '" + branch.Text + "') Group By PurchaseOrder.PONumber", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
This show my query filter. Any tip on how to do if PurchaseOrderEntry.OrderNumber already exist on my records so I can manage which one repeats.
Thank you!
Chris
I added this code now on my works and it is working now.
DataTable dt = new DataTable();
dt.Clear();
dt.Reset();
con.Close();
adaptors1.SelectCommand = con.CreateCommand();
adaptors1.SelectCommand.CommandText = "Select TOP 1 [ponumber],[clref] from [ISSPandayan].[dbo].[" + branch.Text + "] where [ponumber] = '" + dr.Cells["ponumber"].Value + "' ORDER BY [clref] ASC";
adaptors1.Fill(dt);
// select query para malam kung existing ponumber
if (dt.Rows.Count == 1)
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = dt.Rows[0][1].ToString();
}
else
{
adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = " ";
}
//adaptorss.InsertCommand.Parameters.Add("#already", SqlDbType.VarChar).Value = "";
//MessageBox.Show(Convert.ToString(dr.Cells["description"].Value));
con.Close();
con.Open();
adaptorss.InsertCommand.ExecuteNonQuery();
adaptorss.InsertCommand.Parameters.Clear();

DataGrid View Not Showing Newly Added Record using Access Database

I am new to C# and I want to do this ASAP as I've had this problem since past week. I have tried a few approaches and not yet gotten the correct output. Here is my code:
private void btnDelete_Click(object sender, EventArgs e)
{
try
{
String itemcode = tbItemCode.Text.ToString();
String shade = tbShade.Text.ToString();
String rollnumber = tbRollNumber.Text.ToString();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Eranga\Documents\Visual Studio 2010\Projects\RollAllocationModel\RollAllocationModel\Roll.mdb;Persist Security Info=True;Jet OLEDB:Database Password=admin");
String deletequery = "DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + rollnumber + "')";
//String deletequery = "SELECT * FROM TabRoll";
//code by query builder ----> DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + length + "');
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(deletequery, conn);
OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.EndEdit();
bSource.EndEdit();
da.Update(dt);
dataGridView1.DataSource = bSource;
conn.Close();
MessageBox.Show("Data deleted");
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
Why doesn't the DataGrid does not update with the new record.

Setting a button on Gridview row, conditionally

I have a button on my Gridview:
<asp:Button ID="lnk_ship" runat="server" CssClass="btn-mini" Text="Ship Software" />
I am loading my Gridview from SQL, to a Class, then a DataBind() event,
protected void FilterResults(object sender, EventArgs e)
{
var shipments = new List<SoftShipments>();
DateTime dt1 = Convert.ToDateTime(Textbox1.Text);
DateTime dt2 = Convert.ToDateTime(Textbox2.Text);
string cvt1 = "'" + dt1.Year.ToString() + "-" + dt1.Month.ToString() + "-" + dt1.Day.ToString() + "'";
string cvt2 = "'" + dt2.Year.ToString() + "-" + dt2.Month.ToString() + "-" + dt2.Day.ToString() + "'";
string qry = null;
if (Showshipped.Checked)
{
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2;
}
else {
qry = "select * from sft_Ship where sft_Entry_Dt between " + cvt1 + " and " + cvt2 + " and sft_shipped = 'No'";
}
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("softship"));
conn.Open();
SqlCommand cmd = new SqlCommand(qry, conn);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
shipments.Add(new SoftShipments() { index = (int) dr["id"], softtitle = dr["sft_SoftTitle"].ToString(),
productID = dr["sft_ProductID"].ToString(), ver = dr["sft_Version"].ToString(),
custnam = dr["sft_CustName"].ToString(), title = dr["sft_Title"].ToString(),
comp = dr["sft_Company"].ToString(), shipAddr = dr["sft_ShipAddress"].ToString(),
dept = dr["sft_Dept"].ToString(), city = dr["sft_City"].ToString(), state = dr["sft_State"]
.ToString(), postalCd = dr["sft_PostalCd"].ToString(), country = dr["sft_Country"].ToString(),
email = dr["sft_Email"].ToString(), entry_date = dr["sft_Entry_Dt"].ToString(),
ship_date = dr["sft_Ship_Dt"].ToString(), shipped = dr["sft_Shipped"].ToString()
});
}
gdv_Ship.DataSource = shipments;
gdv_Ship.DataBind();
conn.Close();
}
I would like to load the Gridview with the button visible if the value "shipped = 'No' or not visible if 'Yes' ... just not quite certain where to add this code? Any assistance would be appreciated.
Regards,
You could subscribe to the databound event of the grid, and then show/hide the buttons in the template with a FindControl("controlName")

Listview value to combobox

I have this combobox fetching values from SQL:
public void brandSelectCB(ComboBox cb)
{
string sSQL = " SELECT" +
" id, name" +
" FROM" +
" tbBrand" +
" ORDER BY" +
" name";
sqlConnect connect = new sqlConnect();
DataTable dt = new DataTable();
dt = connect.getBD(sSQL);
cb.DataSource = dt;
cb.DisplayMember = "name";
cb.ValueMember = "id";
}
I have also a listview like this:
public void modelSelect(ListView lvModel)
{
string sSQL = " SELECT" +
" tbModel.id, tbBrand.name AS brand, tbModel.name" +
" FROM" +
" tbBrand, tbModel" +
" WHERE" +
" tbBrand.id = tbModel.brand" +
" ORDER BY" +
" tbBrand.name, tbModel.name";
sqlConnect connect = new sqlConnect();
DataTable dt = new DataTable();
dt = connect.getBD(sSQL);
foreach (DataRow dr in dt.Rows)
{
ListViewItem item = new ListViewItem(dr["id"].ToString());
item.SubItems.Add(dr["brand"].ToString());
item.SubItems.Add(dr["name"].ToString());
lvModel.Items.Add(item);
}
}
When I select a row from the listview and click the edit button, it should get the values from that selected row to the corresponding comboboxes and textboxes:
private void btnEdit_Click(object sender, EventArgs e)
{
this.txtID.Text = lvModels.SelectedItems[0].SubItems[0].Text;
this.cbBrand.SelectedText = lvModels.SelectedItems[0].SubItems[1].Text;
this.txtName.Text = lvModels.SelectedItems[0].SubItems[2].Text;
}
but I get no values on the comboboxes, only in the textboxes. I realize that it is because the combo is in dropdownlist style, and i should use SelectedValue or SelectedItem but neither of them seems to work.
Any ideas ?
You might try something like this:
string brandText = lvModels.SelectedItems[0].SubItems[1].Text;
DataRow itemToSelect = ((DataTable) this.cbBrand.DataSource)
.Rows
.Cast<DataRow>()
.FirstOrDefault(r=>r.Field<string>("name").Equals(brandText));
if(itemToSelect != null)
cbBrand.SelectedItem = itemToSelect;
Disclaimer: I didn't test this out; this is from memory.
This would be simpler if you stashed the BrandID somewhere in the ListViewItem: then you could use SelectedValue.

Categories

Resources