Listview value to combobox - c#

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.

Related

Reload all dropdownlist after I clear one dropdown in c#

So, here it is my problem
I have four dropdowns in the screen, and all four are loaded when the screen loads, also when I change the first combobox, all three load with the selectedindex method, no problems in that.
But when I manually clear the first combobox, the remaining three retain the same values as before and I am not able to reset them. Any suggestions ?
private void comboBox_commodity_SelectedIndexChanged(object sender, EventArgs e)
{
//filter stat type
if (!comboBox_commodity.Text.Equals(""))
{
statTypes = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select [ERSStatisticType_Attribute] from " + schemaName + "ERSStatisticType_LU " +
"WHERE ERSStatisticType_ID IN (SELECT DISTINCT[ERSCommodity_ERSStatisticType_ID] FROM "
+ schemaName + "[ERSCommodityDataSeries] WHERE [ERSCommodity_ERSGroup_ID] = " + groupID
+ " and ERSCommoditySubCommodity_ID = " + getCommodityID(comboBox_commodity.Text) + " ) ";
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
statTypes.Add(row["ERSStatisticType_Attribute"].ToString());
}
}
comboBox_statType.DataSource = statTypes;
comboBox_statType.SelectedItem = null;
//filter unit
//filter source
source = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select DISTINCT ERSSource_Desc from " + schemaName
+ "ERSSource_LU where ERSSource_ID IN (SELECT DISTINCT[ERSCommodity_ERSSource_ID] FROM " + schemaName + "[ERSCommodityDataSeries] WHERE [ERSCommodity_ERSGroup_ID] = " + groupID +
" and ERSCommoditySubCommodity_ID = " + getCommodityID(comboBox_commodity.Text) + " ) ORDER BY ERSSource_Desc";
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
source.Add(row["ERSSource_Desc"].ToString());
}
}
comboBox_source.DataSource = source;
comboBox_source.SelectedItem = null;
unit = new List<string>();
foreach (string groupID in groupIds)
{
string sql = "select distinct ERSUnit_Desc from " + schemaName
+ "ERSUnit_LU ulu" + "," + schemaName + "ERSCommodityDataSeries cds" + "," + schemaName + "ERSDataValues dv " +
" where ulu.ERSUnit_ID=dv.ERSDataValues_ERSUnit_ID " +
" and cds.ERSCommoditySubCommodity_ID= " + getCommodityID(comboBox_commodity.Text) +
" and cds.ERSCommodity_ID=dv.ERSDataValues_ERSCommodity_ID " +
" and [ERSCommodity_ERSGroup_ID] = " + groupID;
DataTable dt = GetData(sql);
DataRow[] dr = dt.Select();
foreach (DataRow row in dr)
{
unit.Add(row["ERSUnit_Desc"].ToString());
}
}
comboBox1_unit.DataSource = unit;
comboBox1_unit.SelectedItem = null;
}
else
{
fillCommodityCombobox();
fillSourceCombobox();
fillUnitCombobox();
fillStatTypeCombobox();
}
}
If I manually clear the combobox, all other three values should be loaded with all the revelant values.
Now, I'm not 100% on your utilization here, but based off the initial issue I would use the Textupdate Event Handler like this:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
ClearCmboboxesOnFirstEmpty(comboBox_commodity.Text);
}
private void ClearCmboboxesOnFirstEmpty(string comboValue)
{
if(comboValue == "")
{
fillCommodityCombobox();
fillSourceCombobox();
fillUnitCombobox();
fillStatTypeCombobox();
}
}

how to sort listbox using comboboxC#

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

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

In gridview is not displaying the first row

In gridview that am try to displaying the data in the database but it is ignoring the first row from the tabel & taking the rest of row.., plz suggest me what to do..
below is my code.
protected void Page_Load(object sender, EventArgs e)
{
DBLibrary obj = new DBLibrary();
String Parent = (string)Session["parentName"];
String ss = "Select StudentId from Tbl_Parents where parentName='" + Parent + "'";
SqlDataReader dr6 = obj.ExecuteReader(ss);
dr6.Read();
string id = dr6[0].ToString();
string bind = "SELECT AnuFeeMaster.StudentId, Tbl_Student.SName, AnuFeeMaster.Month, AnuFeeMaster.Year, AnuFeeMaster.FeeAmount, " +
" AnuFeeMaster.PaidAmount FROM AnuFeeMaster INNER JOIN Tbl_Student ON AnuFeeMaster.StudentId = Tbl_Student.StudentId where ( AnuFeeMaster.StudentId ='" + id + "')";//and (AnuFeeMaster.ChkDate='" + date.ToString() + "') ";
SqlDataReader dr = obj.ExecuteReader(bind);
dr.Read();
gv1.DataSource = dr;
gv1.DataBind();
}
Remove the dr.Read(); line.
You are passing the reader already advanced with one position.

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")

Categories

Resources