Textbox autocomplete function not autocompleting in C# WinForm Application - c#

Im having problems with this simple function on a textbox.. I have a winforms application, with a textbox, set up to autocomplete like this:
if (rbSerialNumSearch.Checked)
{
txtSerialNum.Enabled = true;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
//Test data
data.Add("555-777-333");
data.Add("222-333-444");
data.Add("111-222-333");
txtSerialNum.AutoCompleteCustomSource = data;
txtSerialNum.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSerialNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
But it is not working. Nothing appears when i type in the textbox? If i i specify strings directly to the textbox collection property (in design mode), it works fine, but when i try to add strings programmatically, nothing happends?
Thanks in advance..
ENTIRE CODE FOR FORM HERE:
namespace GUI
{
public partial class UpdateEquipmentForm : Form
{
EquipmentManager em;
ProductManager pm;
CategoryManager cm;
public UpdateEquipmentForm()
{
InitializeComponent();
em = new EquipmentManager();
pm = new ProductManager();
cm = new CategoryManager();
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (rbCategorySearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock().Where(eq => eq.Product.Category_Id == (int)cbChooseCategory.SelectedValue).ToList();
var resultset = (from eq in equipments
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
if (rbProductsSearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock().Where(eq => eq.Product.Id == (int)cbChooseType.SelectedValue).ToList();
var resultset = (from eq in equipments
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
if (rbSerialNumSearch.Checked)
{
List<Equipment> equipments = em.GetAllEquipmentInStock();
var resultset = (from eq in equipments
where eq.SerialNumber.Contains(txtSearchEquipment.Text)
select new { eq.Product.ProductNameNum, eq.Id, eq.SerialNumber, eq.InvoiceNumber, eq.CreatedDate, eq.ExpiryDate, eq.FirstUseDate }).ToList();
dgvResult.DataSource = resultset;
}
}
private void rbCategorySearch_CheckedChanged(object sender, EventArgs e)
{
if (rbCategorySearch.Checked)
{
cbChooseCategory.Enabled = true;
cbChooseCategory.DataSource = cm.GetAllActiveCategories();
cbChooseCategory.DisplayMember = "Name";
cbChooseCategory.ValueMember = "Id";
}
else
{
cbChooseCategory.Enabled = false;
}
}
private void rbProductsSearch_CheckedChanged(object sender, EventArgs e)
{
if (rbProductsSearch.Checked)
{
cbChooseType.Enabled = true;
cbChooseType.DataSource = pm.GetAllActiveProducts();
cbChooseType.DisplayMember = "ProductNameNum";
cbChooseType.ValueMember = "Id";
}
else
{
cbChooseType.Enabled = false;
}
}
private void rbSerialNumSearch_CheckedChanged(object sender, EventArgs e)
{
if (rbSerialNumSearch.Checked)
{
txtSerialNum.Enabled = true;
AutoCompleteStringCollection data = new AutoCompleteStringCollection();
data.Add("555-777-333");
data.Add("222-333-444");
data.Add("111-222-333");
txtSerialNum.AutoCompleteCustomSource = data;
txtSerialNum.AutoCompleteMode = AutoCompleteMode.Suggest;
txtSerialNum.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
else
{
txtSerialNum.Enabled = false;
}
}
}
}

Found the problem.. Really stupid of me. I was referencing the wrong textbox :-( The one i should be referencing is called txtSearchSerial and not txtSerialNum. Doh !
Appreciate the effort guys..thanks.

You can set a break point to
txtSerialNum.Enabled = true;
I think this application never run into this block.
Or after this code, you re-set the binding of txtSerialNum.

Related

C# How to shorten Datagridview Selectionchanged code in a clean and proper way of coding

I always wanted my code to be cleaner and readable. I'm here in order to achieve that. Since i'm a beginner, it's better to learn this early. Like calling all of them in a class, I don't want too see these many codes in my form. I hope someone would be able to give me a suggestions and a proper way of doing these.
Here's my code
public partial class SIMSSupplier : UserControl
{
ADDSupplier supply;
ADDPReturns returns;
public SIMSSupplier()
{
InitializeComponent();
}
public DataTable dbdataset;
public DataSet ds = new DataSet();
public string ID = "SPPLR-000";
public int DeliveryID, OrderID, ReturnID;
DataView db;
DataTable dt = new DataTable();
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentCell.RowIndex;
SupplierID.Text = Supplierview.Rows[row].Cells[0].Value.ToString();
CompanyName.Text = Supplierview.Rows[row].Cells[1].Value.ToString();
ContactName.Text = Supplierview.Rows[row].Cells[2].Value.ToString();
ContactNumber.Text = Supplierview.Rows[row].Cells[3].Value.ToString();
Date.Text = Supplierview.Rows[row].Cells[4].Value.ToString();
Address.Text = Supplierview.Rows[row].Cells[5].Value.ToString();
Remarks.Text = Supplierview.Rows[row].Cells[6].Value.ToString();
}
private void PurchaseOrder_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseOrder.CurrentCell.RowIndex;
txt_purchase.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
txt_supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
txt_item.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
txt_date.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
txt_quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
txt_cost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
txt_amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
txt_sales.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
txt_code.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
txt_patient.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseDeliveries_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseDeliveries.CurrentCell.RowIndex;
PurchaseID.Text = PurchaseDeliveries.Rows[row].Cells[0].Value.ToString();
Supplier.Text = PurchaseDeliveries.Rows[row].Cells[1].Value.ToString();
ItemDescription.Text = PurchaseDeliveries.Rows[row].Cells[2].Value.ToString();
Dates.Text = PurchaseDeliveries.Rows[row].Cells[3].Value.ToString();
Quantity.Text = PurchaseDeliveries.Rows[row].Cells[4].Value.ToString();
Unitcost.Text = PurchaseDeliveries.Rows[row].Cells[5].Value.ToString();
Amount.Text = PurchaseDeliveries.Rows[row].Cells[6].Value.ToString();
SalesInvoice.Text = PurchaseDeliveries.Rows[row].Cells[7].Value.ToString();
Codeitems.Text = PurchaseDeliveries.Rows[row].Cells[8].Value.ToString();
Patientname.Text = PurchaseDeliveries.Rows[row].Cells[9].Value.ToString();
}
private void PurchaseReturn_SelectionChanged(object sender, EventArgs e)
{
var row = PurchaseReturn.CurrentCell.RowIndex;
txt_return.Text = PurchaseReturn.Rows[row].Cells[0].Value.ToString();
txt_rsupplier.Text = PurchaseReturn.Rows[row].Cells[1].Value.ToString();
txt_ritem.Text = PurchaseReturn.Rows[row].Cells[2].Value.ToString();
txt_rmodel.Text = PurchaseReturn.Rows[row].Cells[3].Value.ToString();
txt_rsrp.Text = PurchaseReturn.Rows[row].Cells[4].Value.ToString();
txt_rcode.Text = PurchaseReturn.Rows[row].Cells[5].Value.ToString();
txt_rdate.Text = PurchaseReturn.Rows[row].Cells[6].Value.ToString();
txt_rremarks.Text = PurchaseReturn.Rows[row].Cells[7].Value.ToString();
}
}
the first can simplify as the following:
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var row = Supplierview.CurrentRow;
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
the second , i would recommend use objects collection as a datasource for your grid. For example :
class DataItem{
public string SupplierID {get;set;}
public string CompanyName {get;set;}
.....
}
Supplierview.DataSource = "collection of DataItem"
then
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
var dataItem = dataGridView1.CurrentRow.DataBoundItem as DataItem;
if (dataItem != null)
{
SupplierID.Text = dataItem.SupplierID;
.....
}
}
I suggest using DataBinding for this, then there is no code needed to perform the actions in your sample.
If you dont want to use databinding you could simply make use of private methods to organize your code.
For example
#region Supplier Stuff
private void SupplierViewChanged(DataRow row)
{
SupplierID.Text = row.Cells[0].Value.ToString();
CompanyName.Text = row.Cells[1].Value.ToString();
ContactName.Text = row.Cells[2].Value.ToString();
ContactNumber.Text = row.Cells[3].Value.ToString();
Date.Text = row.Cells[4].Value.ToString();
Address.Text = row.Cells[5].Value.ToString();
Remarks.Text = row.Cells[6].Value.ToString();
}
// put all other helper methods that deal with Supplier here...
#endregion Supplier Stuff
private void Supplierview_SelectionChanged(object sender, EventArgs e)
{
SupplierViewChanged(Supplierview.CurrentRow);
}
This makes your code a bit more organized and readable, but databinding is still the method I would choose

How to bind a many-to-many relation in WinForms?

I have the following DataSet:
The Product and Part tables can be edited using these DataGridViews:
When the user double-clicks a row in the Products grid, the following form opens:
The left column is supposed to list the parts associated with this product. The right column is supposed to list all the other parts. Using the << and >> buttons, the user should be able to choose which parts belong to the current product.
I have done something similar with a one-to-many relation and it worked perfectly. The code was as follows:
public partial class ProductPartsForm : Form
{
private int _productID;
private DataSet1 _data;
public ProductPartsForm(DataSet1 data, DataRowView productRowView)
{
var productRow = (DataSet1.ProductRow)productRowView.Row;
_productID = productRow.ID;
_data = data;
InitializeComponent();
productBindingSource.DataSource = productRowView;
assignedPartBindingSource.DataSource = productBindingSource;
assignedPartBindingSource.DataMember = "FK_Product_Part";
assignedPartsListBox.DisplayMember = "Name";
unassignedPartBindingSource.DataSource = _data;
unassignedPartBindingSource.DataMember = "Part";
unassignedPartsListBox.DisplayMember = "Name";
unassignedPartBindingSource.Filter = $"isnull(ProductID, 0) = 0";
}
private void assignButton_Click(object sender, EventArgs e)
{
var partRowView = (DataRowView)unassignedPartBindingSource.Current;
var partRow = (DataSet1.PartRow)partRowView.Row;
var productRowView = (DataRowView)productBindingSource.Current;
var productRow = (DataSet1.ProductRow)productRowView.Row;
partRow.ProductRow = productRow;
UpdateUI();
}
private void unassignButton_Click(object sender, EventArgs e)
{
var partRowView = (DataRowView)assignedPartBindingSource.Current;
var partRow = (DataSet1.PartRow)partRowView.Row;
partRow.SetProductIDNull();
UpdateUI();
}
private void UpdateUI()
{
assignedPartsListBox.Refresh();
unassignedPartsListBox.Refresh();
assignButton.Enabled = unassignedPartsListBox.Items.Count > 0;
unassignButton.Enabled = assignedPartsListBox.Items.Count > 0;
}
}
With the many-to-many relation, there are two things I couldn't get to work:
The left column doesn't show the names of the parts. It should display lowercase letters, like the right column; instead, it shows the string System.Data.DataRowView. I want to fix this using some sort of lookup, but I don't know how.
When you press <<, the selected part stays on the right column instead of moving to the left column. If you try to press << again with the same part, you get the following error:
System.Data.ConstraintException: 'Column 'ProductID, PartID' is constrained to be unique. Value '-4, -3' is already present.'
(which is understandable). I think this can be fixed using a filter expression, but I'm not sure how to write it and how to update the right column automatically after every change.
Has anyone done something similar and can help point me in the right direction?
Here's what I finally came up with. The key function is UpdateFilters, which creates a list of part IDs assigned to the current product and then filters the two columns "manually" using the IN and NOT IN operators.
public partial class ProductPartsForm : Form
{
private int _productID;
private DataSet1 _data;
public ProductPartsForm(DataSet1 data, DataRowView productRowView)
{
var productRow = (DataSet1.ProductRow)productRowView.Row;
_productID = productRow.ID;
_data = data;
InitializeComponent();
productBindingSource.DataSource = productRowView;
assignedPartBindingSource.DataSource = _data;
assignedPartBindingSource.DataMember = "Part";
assignedPartsListBox.DisplayMember = "Name";
unassignedPartBindingSource.DataSource = _data;
unassignedPartBindingSource.DataMember = "Part";
unassignedPartsListBox.DisplayMember = "Name";
}
private void ProductPartsForm_Load(object sender, EventArgs e)
{
UpdateFilters();
UpdateUI();
}
private void assignButton_Click(object sender, EventArgs e)
{
var partRowView = (DataRowView)unassignedPartBindingSource.Current;
var partRow = (DataSet1.PartRow)partRowView.Row;
var productRowView = (DataRowView)productBindingSource.Current;
var productRow = (DataSet1.ProductRow)productRowView.Row;
_data.ProductPart.AddProductPartRow(productRow, partRow);
UpdateFilters();
UpdateUI();
}
private void unassignButton_Click(object sender, EventArgs e)
{
var partRowView = (DataRowView)assignedPartBindingSource.Current;
var partRow = (DataSet1.PartRow)partRowView.Row;
var productPartRow = _data.ProductPart
.Single(pp => pp.ProductID == _productID && pp.PartID == partRow.ID);
_data.ProductPart.RemoveProductPartRow(productPartRow);
UpdateFilters();
UpdateUI();
}
private void UpdateFilters()
{
var assignedIds = _data.ProductPart
.Where(pp => pp.ProductID == _productID)
.Select(pp => pp.PartID.ToString());
if (assignedIds.Any())
{
assignedPartBindingSource.Filter = $"ID IN ({string.Join(",", assignedIds)})";
unassignedPartBindingSource.Filter = $"ID NOT IN ({string.Join(",", assignedIds)})";
}
else
{
assignedPartBindingSource.Filter = "FALSE";
unassignedPartBindingSource.RemoveFilter();
}
}
private void UpdateUI()
{
assignedPartsListBox.Refresh();
unassignedPartsListBox.Refresh();
assignButton.Enabled = unassignedPartsListBox.Items.Count > 0;
unassignButton.Enabled = assignedPartsListBox.Items.Count > 0;
}
}

dgv selectionchanged c# winforms

Im facing a very weird issue, wich should be very simple.
What im trying to achieve: I have 2 datagrids: 1 with invoiceheaders and 1 with invoiceDetails.
When i click on a particular row from the invoiceheaders, the invoicedetails need to change and show the particular details of that invoice. The event im using for this is dgvInvoiceHeaders_SelectionChanged.
So the code in the view:
private void InvoiceListView_Load(object sender, EventArgs e)
{
int invoiceId = 1;
invoiceHeadersBinding.DataSource = invoiceListPresenter.getInvoiceHeaders();
dgvInvoiceHeaders.DataSource = invoiceHeadersBinding;
setInvoiceHeaderColumns();
if (dgvInvoiceHeaders.CurrentRow != null)
{
Int32.TryParse(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString(), out invoiceId);
}
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(invoiceId);
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
private void dgvInvoiceHeaders_SelectionChanged(object sender, EventArgs e)
{
dgvInvoiceDetails.DataSource = invoiceListPresenter.getSelectedInvoiceDetails(Convert.ToInt32(dgvInvoiceHeaders.CurrentRow.Cells[0].FormattedValue.ToString()));
dgvInvoiceDetails.DataSource = invoiceListPresenter.invoiceDetails;
setInvoiceDetailColumns();
}
And this is the code of the methods im calling:
public List<tbl_invoices> invoiceHeaders;
public BindingList<tbl_invoices> getInvoiceHeaders()
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoice = from i in invoices.tbl_invoices
select i;
invoiceHeaders = invoice.ToList();
var listBinding = new BindingList<tbl_invoices>(invoiceHeaders);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
public List<tbl_invoiceDetail> invoiceDetails;
public BindingList<tbl_invoiceDetail> getSelectedInvoiceDetails(int invoiceID)
{
try
{
using (var invoices = new DBCrownfishEntities())
{
invoices.Configuration.LazyLoadingEnabled = false;
var invoiceDetail = from i in invoices.tbl_invoiceDetail
where i.InvoiceID == invoiceID
select i;
invoiceDetails = invoiceDetail.ToList();
var listBinding = new BindingList<tbl_invoiceDetail>(invoiceDetails);
return listBinding;
}
}
catch (Exception exe)
{
throw exe;
}
}
But with this example the formload is loaded correctly. But after the event is fired, my invoiceheader datagrid is empty. When i put the text in comment at the method dgvInvoiceHeaders_selectionChanged(), I see that both of the datagrids are filled correctly.
A push in the right direction would be very kind.

Creating a Listview filter in WPF with a text box search

I am creating an application with an XML file called star.xml to store my data in a list view. I am very new to c# and programming and need any help
Basically, I want to be able to type in my search text box (called 'search') and for my list view (lstStar) to only show the matching records. I.e. typing in 'Audi' will only return those items.
any help will be much appreciated
jen
namespace StarinCar
{
public partial class MainWindow : Window
{
int hot = -2;
int Mildly_Moist = -2;
int Wet = -4;
int Very_Wet = -6;
private ObservableCollection<star> starData;
public MainWindow()
{
InitializeComponent();
starData = new ObservableCollection<star>();
lstStar.ItemsSource = starData;
try
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamReader rd = new StreamReader("star.xml"))
{
starData = xs.Deserialize(rd) as ObservableCollection<star>;
}
}
catch
{
}
lstStar.ItemsSource = starData;
lblAverage.Content = starData.Average(i => i.time).ToString();
lblFastest.Content = starData.Min(i => i.time).ToString();
lblSlowest.Content = starData.Max(i => i.time).ToString();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
star newStar = new star();
newStar.firstName = txtName.Text;
newStar.time = int.Parse(txtTime.Text);
newStar.car = txtCar.Text;
newStar.track = txtTrack.Text;
starData.Add(newStar);
if (txtTrack.Text.Contains("Hot") || (txtTrack.Text.Contains("hot") == true))
{
newStar.time = int.Parse(txtTime.Text) + hot;
}
if (txtTrack.Text.Contains("Mildly Moist") || (txtTrack.Text.Contains("mildly moist")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Mildly_Moist;
}
if (txtTrack.Text.Contains("Wet") || (txtTrack.Text.Contains("wet") == true))
{
newStar.time = int.Parse(txtTime.Text) + Wet;
}
if (txtTrack.Text.Contains("Very Wet") || (txtTrack.Text.Contains("very wet")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Very_Wet;
}
}
private void Window_Closed(object sender, EventArgs e)
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamWriter wr = new StreamWriter("star.xml"))
{
xs.Serialize(wr, starData);
}
}
}
}
You could use ICollectionView. So you would have your "overall"
star collection 'starData'. But your listbox itemssource would be bound to something like this:
public ICollectionView FilteredStars
{
get
{
ICollectionView source = CollectionViewSource.GetDefaultView(starData);
source.Filter = new Predicate<object>(FilterStars);
return source;
}
}
the logic that does the filtering here:
private bool FilterStars(object item)
{
bool b = false;
star a = item as star;
if (a != null)
{
if (a.Name.Contains(searchBoxText)) //your filter logic here
{
b = true;
}
else if String.IsNullOrWhiteSpace(searchBoxText)
{
b = true;
}
}
return b;
}
Basically, you have your main collection, then some logic that filters your main collection to a filtered collection, and that's what you should set itemssource of your listbox to. This, so far, is assuming you are going to put some kind of property change into your search text box and probably then click a button, like "Search" to then tell the list to check and re-populate to match the search term.
This is how I filter in a similar application
public IEnumerable<string> PastEntries1
{
get
{
if(string.IsNullOrEmpty(textValue))
{
return FieldDefString.PastEntries;
}
else
{
return FieldDefString.PastEntries.Where(x => x.StartsWith(textValue, StringComparison.OrdinalIgnoreCase));
}
}
}

objects in datagridview

Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}
That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)
I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);
If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code

Categories

Resources