Multiple combo boxes to query a data table issue - c#

I'm putting together a project that has a form to fill out which then populates a query from a separate data table. It will always only grab one row based on the inputs, which is then used for a price calculation. I have two places in the code using the same setup. The first one uses a single combo box for the query and it works great, but the second part uses two combo boxes to make an "AND" query and I can't figure out why it isn't working, it doesn't seem to recognize the selections and place them into the calculation. Below is the code for that part, any help would be appreciated!
private void plant_AmountTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
try
{
plantamountResult = Convert.ToDecimal(plant_AmountTextBox.Text);
}
catch (Exception)
{
MessageBox.Show("Please enter a valid amount");
}
try
{
DataRowView rowviewpml = material_NameComboBox.SelectedItem as DataRowView;
materialNameSelection = "";
if (rowviewpml != null)
{
materialNameSelection = rowviewpml.Row["Material_Species"] as string;
}
DataRowView rowviewst = stockComboBox.SelectedItem as DataRowView;
stockSelection = "";
if (rowviewst != null)
{
stockSelection = rowviewst.Row["Stock_Type"] as string;
}
string mcSearch = "Material_Species = '" + materialNameSelection + "' AND Stock_Type = '" + stockSelection + "'";
Plant_Material_PricingTableAdapter pmpTA = new Plant_Material_PricingTableAdapter();
DataTable pmpDT = pmpTA.GetData();
DataRow[] pmpRow = pmpDT.Select(mcSearch);
foreach(DataRow row in pmpRow)
{
materialEstCost = Convert.ToDouble(pmpRow[0]["Previous_FY_Quotes"]);
}
plantestCostCalc.Text = "$" + ((decimal)materialEstCost * plantamountResult).ToString();
}
catch
{
plantestCostCalc.Text = "0";
}
}

Related

How to change color of different rows in datagrid c# windows ce

I try to develop a c# application(gathering products by their barcodes) to windows ce handheld device with compact framework 3.5
I have a datagrid and datagrid is bind with a datatable by sql. There are 4 columns in my datagrid, 3rd column represents the quantity of the products needs to be collected, and last column comes with the default value 0(quantity collected). Whenever user enters a product code, quantity of the product increases 1 by 1.
I want to make background color of the row blue when user enters corresponding product code(to show which product is being collected)
and also I want to make background color green if user collects the needed products.
I tried coloring row by selected index but it does not work. When selection gone , colours are gone.
Here is a picture of screen when needed quantity of product was collected.
Here is when I want to see the processed row.
Below is my code of the keypress event of the textbox(entering of product code)
private void txtUrunkod_KeyPress(object sender, KeyPressEventArgs e)
{
foreach (System.Data.DataColumn col in dt.Columns) col.ReadOnly = false;
if (e.KeyChar == (char)Keys.Enter)
{
islemkod = txtUrunkod.Text;
islemkod.Trim();
if (islemkod.Contains('/'))
{
serikodbol = islemkod.Split('/');
urunKodum = serikodbol[0];
DataRow row = dt.Select("urunkodu='" + urunKodum + "'").FirstOrDefault();
int guncelle = Convert.ToInt32(row[3]);
guncelle++;
row[3] = guncelle;
}
else if (islemkod.Length == 8)
{
SqlCommand cmd = new SqlCommand("exec MY_TOPUK_BILGI_GETIR '" + islemkod + "'", conStr);
conStr.Open();
SqlDataReader dr = cmd.ExecuteReader();
uk = new DataTable();
uk.Load(dr);
conStr.Close();
//toplamaGrid.Select(0);
foreach (DataRow row2 in uk.Rows)
{
urunKodum = row2[0].ToString();
}
DataRow row = dt.Select("urunkodu='" + urunKodum + "'").FirstOrDefault();
int guncelle = Convert.ToInt32(row[3]);
guncelle++;
row[3] = guncelle;
int index = -1;
bool found = false;
foreach (DataRow datr in dt.Rows)
{
index++;
string d = datr["urunkodu"].ToString();
if (datr[0].ToString() == urunKodum)
{
found = true;
break;
}
}
if (found && !row[2].Equals(row[3]))
{
toplamaGrid.Select(index);
toplamaGrid.SelectionBackColor = Color.Blue;
}
else if (row[2].Equals(row[3]))
{
toplamaGrid.Select(index);
toplamaGrid.SelectionBackColor = Color.Green;
//toplamaGrid.UnSelect(index);
}
}
else if (islemkod.Length == 7 && islemkod[0] == 'P')
{
}
else//islemkod.Length != 8 && !islemkod.Contains('/')
{//
urunKodum = txtUrunkod.Text;
txtUrunkod.Visible = false;
lblurunkod.Visible = false;
txtifAdres.Visible = true;
lbladressor.Visible = true;
txtifAdres.Focus();
}
updated = true;
txtUrunkod.Text = "";
sonindex = 0;
}
}
I couldnt find many info about this. Any help will be important. Thanks for any help!
First of all I experienced the same problem. Make use of DataGridFormatCellEventArgs for coloring the solution.
explained here Add the DataGrid file to your code in the link. (DataGridFormatCellEventArgs.cs and FormattableTextBoxColumn.cs) These files contain the Paint class that was used to do the coloring.
different example
I hope I could help. If you experience difficulties, I can give an example from my own code.

datagridview dont let me change the values of the celll

I'm new in c# , but i can do the basics. i need to change all the values of a column and then update the datagrid. The values are in 20170202 format and i want them like 2017-02-02. the method i did works fine but when i try to set the value to the column it wont change.
here is the code:
private void fixAlldates(DataGridView dataGridView2)
{
string aux1 = "";
for (int x = 0; x < dataGridView2.Rows.Count; x++)
{
if (dataGridView2.Rows[x].Cells[4].Value.ToString() != null)
{
aux1 = dataGridView2.Rows[x].Cells[4].Value.ToString();
dataGridView2.Rows[x].Cells[4].Value = fixDate(aux1);
}
if (dataGridView2.Rows[x].Cells[5].Value.ToString() != null)
{
dataGridView2.Rows[x].Cells[5].Value = fixDate(dataGridView2.Rows[x].Cells[5].Value.ToString());
}
dataGridView2.Refresh();
MessageBox.Show(fixDate(aux1); ----> shows result like i want ex: 2017-02-02
MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); ----> shows 2070202
}
}
private string fixDate(string p)
{
if (p == null) return "No especificado";
String fecha = "" + p.Substring(0, 4) + "-" + p.Substring(4, 2) + "-" + p.Substring(6, 2) + "";
return fecha;
}
sorry for my bad english , im a little bit rusty
Edit:
I fill the data with bindingSource.
private void LlenarProductos(string rut)
{
this.rut = rut;
POLbindingSource1.DataSource = null;
dataGridView2.DataSource = null;
DataClasses1DataContext dc = new DataClasses1DataContext();
dc.CommandTimeout = 0;
System.Data.Linq.Table<ASE_PRODUCTOASEGURADO> producto = dc.GetTable<ASE_PRODUCTOASEGURADO>();
var todoprod = from p in producto
where p.RUT == int.Parse(rut)
select new
{
p.POLIZA,
p.SOCIO,
p.SUCURSAL,
p.COD_PROPUESTA,
p.FECHA_ALTA_COTI,
p.FECHA_ALTA_VCTO,
p.NOMBRE_PRODUCTO
};
POLbindingSource1.DataSource = todoprod; // binding source
dataGridView2.DataSource = POLbindingSource1; // filll
this.dataGridView2.Columns["POLIZA"].HeaderText = "Poliza";
this.dataGridView2.Columns["Socio"].HeaderText = "Socio";
this.dataGridView2.Columns["Sucursal"].HeaderText = "Sucursal";
this.dataGridView2.Columns["COD_PROPUESTA"].HeaderText = "Propuesta";
this.dataGridView2.Columns["FECHA_ALTA_COTI"].HeaderText = "Fecha Cotizacion";
this.dataGridView2.Columns["FECHA_ALTA_VCTO"].HeaderText = "Fecha Vencimiento";
this.dataGridView2.Columns["NOMBRE_PRODUCTO"].HeaderText = "Producto";
// fixAlldates(dataGridView2);
}
From msdn https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.value(v=vs.110).aspx.
The Value property is the actual data object contained by the cell.
So basically the line MessageBox.Show(dataGridView2.Rows[x].Cells[4].Value.ToString()); is getting the value of the underlying data, whereas MessageBox.Show(fixDate(aux1); is actually formatting the date as you require.
You're overlooking the fact that although you're seeing the data in the grid in a specific way, you're not actually changing the data itself.
UPDATE
To actually edit the data in a cell see here

Get the Row ID dynamically in the query

Suppose if I have 4 rows in the gridview and I want to delete only second row so how to get the dynamic ID from the table so that I can delete that particular row with unique ID
Here is my query, but I am not able to bring the respective ID:-
protected void GrdTraining_DeleteCommand(object sender, Obout.Grid.GridRecordEventArgs e)
{
if (Session["dt10"] != null)
{
dt10 = (DataTable)Session["dt10"];
}
else
{
BindDatatable();
}
DataRow[] grdTrain = dt10.Select("SR_NO=" + Convert.ToString(e.Record["SR_NO"]));
dt10.Rows.Remove(grdTrain[0]);
AddToViewState("GrdTraining");
CF.ExecuteDT("DELETE FROM EMP_ATTACHED_DOCUMENTS where mkey="+ ); // mkey is my unique column in the table, how to get the ID here for the row which I want to delete ??
}
Please suggest
After so much of discussion with Quan Nguyen. And with my team. Finally I got the solution which worked for me.
The logic was simple but was confused with the relation of the SQL Query
Here is the code:-
protected void GrdTraining_DeleteCommand(object sender, Obout.Grid.GridRecordEventArgs e)
{
if (Session["dt10"] != null)
{
dt10 = (DataTable)Session["dt10"];
}
else
{
BindDatatable();
}
DataRow[] grdTrain = dt10.Select("SR_NO=" + Convert.ToString(e.Record["SR_NO"]));
dt10.Rows.Remove(grdTrain[0]);
AddToViewState("GrdTraining");
string strempcode = CF.ExecuteScaler("select emp_card_no from emp_mst a, user_mst b where a.mkey=b.employee_mkey and b.mkey=" + Session["UserId"]);
CF.ExecuteDT("DELETE FROM EMP_ATTACHED_DOCUMENTS where category_id = 'TC' and pk1_value='" + strempcode + "' and document_id='" + e.Record["SR_NO"] + "'");
}

Remove duplicate values in list box

I have a list box and I bind it to my table Position and display the column Position. I inserted 2 values w/ the same position in my table and my list box displays 2 of the same values that i inserted. So, can you help me display only one of the same value in my list box?
i only have this code so far:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
string select;
select = listBox1.SelectedValue.ToString();
dataGridView1.DataSource = this.mAINDATABASEDataSet.tblPosition.Select("Position like '%" + select + "%'");
int numRows = dataGridView1.Rows.Count;
txtCount.Text = Convert.ToString(numRows);
txtSearchCategory.Text = select.ToString();
try
{
MAINDATABASEDataSet.tblCategorizationDataTable GetCategoryCommand1 = GetCategoryData(this.txtSearchCategory.Text.Trim());
MAINDATABASEDataSet.tblCategorizationRow GetCategoryCommand2 = (MAINDATABASEDataSet.tblCategorizationRow)GetCategoryCommand1.Rows[0];
this.txtSG.Text = GetCategoryCommand2.SalaryGrade.ToString();
this.txtMales.Text = GetCategoryCommand2.Male.ToString();
this.txtFemales.Text = GetCategoryCommand2.Female.ToString();
}
catch
{
MessageBox.Show("This Position is not saved yet!", "Information".ToUpper(), MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
txtSG.Text = "";
txtMales.Text = "";
txtFemales.Text = "";
}
}
catch
{
return;
}
}
You can do this by selecting distinct in LINQ. Try this for your data source:
dataGridView1.DataSource = this.mAINDATABASEDataSet
.GroupBy(i => i.Position)
.Select(i => i.First())
.Where(i => i.Position.Contains(select));
include using System.Linq; namespace in your project or reference it. Let me know if this works for you.

Combobox does not revert to null when value is cleared

Due to a flaw in .NET (Microsoft says its intended but I see it as a serious flaw)
If a user empties a combo box (i.e. wants to blank out the value) the selected value does not revert to null instead it keeps the last valid selected value, so when you save with a blank combobox it goes back to the original value.One workaround is to first choose a different option from the drop down, then blank it out and it will work properly. However, that's not something users of an application would prefer.
So is there a way that I can fix this. Or is it possible that I can add an option for "NONE" which will then change the value in the database to NULL. Note: Combobox has data-binding and I was not able to add the option none for Names.
Contents of the Form.Desginer.cs:
private void InitializeComponent()
{
......
this.cmbSecCSR = new System.Windows.Forms.ComboBox();
this.csrBindingSource2 = new System.Windows.Forms.BindingSource(this.components);
.....
//
// pnlCSRs
//
this.pnlCSRs.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.pnlCSRs.Controls.Add(this.cmbSecCSR);
......
//
// cmbSecCSR
//
this.cmbSecCSR.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.cmbSecCSR.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.cmbSecCSR.DataSource = this.csrBindingSource2;
this.cmbSecCSR.DisplayMember = "Name";
this.cmbSecCSR.FormattingEnabled = true;
this.cmbSecCSR.Location = new System.Drawing.Point(112, 26);
this.cmbSecCSR.Margin = new System.Windows.Forms.Padding(0);
this.cmbSecCSR.Name = "cmbSecCSR";
this.cmbSecCSR.Size = new System.Drawing.Size(184, 21);
this.cmbSecCSR.TabIndex = 2;
this.cmbSecCSR.ValueMember = "Username";
this.cmbSecCSR.TextChanged += new System.EventHandler(this.comboBox_TextChanged);
this.cmbSecCSR.Enter += new System.EventHandler(this.cmbBox_Entered);
//
// csrBindingSource2
//
this.csrBindingSource2.DataMember = "CSR";
this.csrBindingSource2.DataSource = this.productionDS;
//..............
}
Above are the bits and pieces related to this combobox (I'm just fixing bugs in the application, and a newbie in C#.
The contents related to this combobox in the .CS file are the following:
private void loadDetails()
{
this.productionCrewTableAdapter.FillByProductionID(this.productionDS.ProductionCrew, productionID);
cmbSecCSR.DataBindings.Add("SelectedValue", productionMasterBindingSource, "CSR2", true, DataSourceUpdateMode.OnPropertyChanged);
}
private void comboBox_TextChanged(object sender, EventArgs e)
{
ComboBox cmbx = (ComboBox)sender;
if (cmbx.Equals(cmbCamSupplier))
{
}
else if (cmbx.Equals(cmbLGSupplier))
{
}
if (cmbx.Text.Length > 0) return;
cmbx.ResetText();
cmbx.SelectedIndex = -1;
}
private void cmbBox_Entered(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
String txt = cmb.Text;
if (cmb.Name.Contains("CSR"))
{
if (cmb != null)
{
((BindingSource)cmb.DataSource).Filter = (cmbOffice.SelectedIndex > -1 ? "Office = '" + cmbOffice.SelectedValue + "' AND " : "") + "IsCSR=1 AND Status=1";
cmb.Text = txt;
}
}
else if (cmb.Name.Contains("RC"))
{
int department = 0;
if (cmb != null)
{
if (cmb.Name.Contains("Camera"))
department = 2;
else if (cmb.Name.Contains("LG"))
department = 3;
else if (cmb.Name.Contains("Power"))
department = 4;
((BindingSource)cmb.DataSource).Filter = (cmbOffice.SelectedIndex > -1 ? "Office = '" + cmbOffice.SelectedValue + "' AND " : "") + "IsCSR=0 AND Status=1 AND (Department = " + department + " OR Department is null OR Department = 0)";
cmb.Text = txt;
}
}
}
If anyone can help me with this issue that I have been struggling with for a while, I'd really really appreciate it.
At the same time to your call clearing values with
this.cmbSecCSR.Items.Clear()
You have to do a
this.cmbSecCSR.Text = ""
or
this.cmbSecCSR.Text = "Default Text"
To clear the selected text in the combobox.

Categories

Resources