Im at beginner level and have tried for a while now. Im trying to remove an item from a ListBox with the help of a remove button. The code is not giving away any errors but the items is not disappearing from the list.
This is the part im struggling with
void taBort()
{
listboxKontakter.SelectedItems.Remove(listboxKontakter.SelectedItems);
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
Here is my entire code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace adressboken
{
public partial class Form1 : Form
{
List<Kontakter> kontaktLista = new List<Kontakter>();
Kontakter person;
string path = "kontakter.txt";
public Form1()
{
InitializeComponent();
}
private void LäggTill_Click(object sender, EventArgs e)
{
person = new Kontakter();
person.FullständigtNamn = textboxNamn.Text;
person.Gatuadress = textboxGatuadress.Text;
person.PostnummerOrt = textboxPostnummerOrt.Text;
person.Födelsedag = textboxFödelsedag.Value;
person.Email = textboxEmail.Text;
person.Anteckningar = textboxAnteckningar.Text;
kontaktLista.Add(person);
listboxKontakter.DataSource = null;
listboxKontakter.DisplayMember = "FullständigtNamn";
listboxKontakter.DataSource = kontaktLista;
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
textboxAntal.Text = kontaktLista.Count.ToString();
}
private void Rensa_Click(object sender, EventArgs e)
{
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
void taBort()
{
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
private void Form1_Load(object sender, EventArgs e)
{
kontaktLista = new List<Kontakter>();
string line = "";
StreamReader sr = new StreamReader(path);
while ((line = sr.ReadLine()) != null)
{
string[] listarray = line.Split(',');
person = new Kontakter();
person.FullständigtNamn = listarray[0];
person.Gatuadress = listarray[1];
person.PostnummerOrt = listarray[2];
person.Email = listarray[3];
person.Födelsedag = Convert.ToDateTime(listarray[4]);
person.Anteckningar = listarray[5];
kontaktLista.Add(person);
}
sr.Close();
listboxKontakter.DataSource = kontaktLista;
listboxKontakter.DisplayMember = "FullständigtNamn";
}
public void listboxKontakter_Click(object sender, EventArgs e)
{
person = (Kontakter)listboxKontakter.SelectedItem;
textboxNamn.Text = person.FullständigtNamn;
textboxGatuadress.Text = person.Gatuadress;
textboxPostnummerOrt.Text = person.PostnummerOrt;
textboxEmail.Text = person.Email;
textboxFödelsedag.Value = person.Födelsedag;
var selectedindex = listboxKontakter.SelectedItems;
}
private void Spara_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(path);
foreach (Kontakter k in kontaktLista)
{
sw.WriteLine(k.FullInfo);
}
sw.Close();
}
private void taBortToolStripMenuItem_Click(object sender, EventArgs e)
{
taBort();
}
private void TaBort_Click(object sender, EventArgs e)
{
taBort();
}
}
}
Your code seems to remove all selected items, and does not refresh.
How about:
listboxKontakter.SelectedItems.Remove(listboxKontakter.SelectedItem);
listboxKontakter.Refresh();
You remove only the single selected item, then refresh your listbox.
If you want to remove ALL items try:
listboxKontakter.Items.Clear();
If you use a DataSource try:
listboxKontakter.DataSource = null;
If all else fails you could loop through the collection and RemoveAt:
for(int i=listboxKontakter.Items.Count; i > -1; i--) {
{
listboxKontakter.Items.RemoveAt(i);
}
Based on a bit of chatting, this should work for you:
void taBort()
{
var newList = (List<Kontakter>)listboxKontakter.DataSource;
var ds = newList.Where(k => k.FullständigtNamn != ((Kontakter)listboxKontakter.SelectedItem).FullständigtNamn).ToList();
listboxKontakter.DataSource = ds;
listboxKontakter.DisplayMember = "FullständigtNamn";
textboxAnteckningar.Clear();
textboxGatuadress.Clear();
textboxNamn.Clear();
textboxPostnummerOrt.Clear();
textboxEmail.Clear();
textboxFödelsedag.Value = DateTime.Now;
}
If you want to remove several items at once try:
var ds = newList.Where(k => !listboxKontakter.SelectedItems.Contains(k.FullständigtNamn)).ToList();
How about:
listboxKontakter.Items.Remove(itemthatneedstoberemoved)
and
listboxKontakter.Items.Clear();
(I assume you called the listbox, listboxKontakter?)
:
Take a look at this
.SelectedItems is basically just an array list of what items you have selected, so you will need to access those like this .SelectedItems[0] .SelectedItems[1].
However the above code even with the [0], [1] will only remove them from the selected list not the actual list box.
If you want to remove them from the list box you need to use the .Items.Remove call.
while(listboxKontakter.SelectedItems.Count >0)
{
listboxKontakter.Items.Remove(listboxKontakter.SelectedItems[0]);
}
EDIT:
If it is a single select listbox all you have to do is
listboxKontakter.Items.Remove(listboxKontakter.SelectedItem);
Related
I am trying to get the cell value in a string from the selected cell in the "Document Number" column in a DataGridView. My code to retrieve data from SharePoint and populate the DataGridView works fine, but I seem to be caught in a loop there? I cannot execute any other methods after populating the DataGridView . I can select a new search term and execute the Button1_Click event again successfully, but I cannot get any other methods to execute?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
using SP = Microsoft.SharePoint.Client;
namespace BuyersForeverFriend
{
public partial class Form1 : System.Windows.Forms.Form
{
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string userSearch = textBox1.Text;
button1.Enabled = true;
}
private void button1_Click(object sender, EventArgs e)
{
using (ClientContext ctx = new ClientContext("https://teamsites.nafta.fcagroup.com/sites/PSOAPPS/iws/"))
{
var userInput = textBox1.Text;
Web web = ctx.Web;
List list = web.Lists.GetById(new Guid("61ef6657-eff7-42cb-99e1-8afd590334ec"));
var q = new CamlQuery() { ViewXml = "<View><Query><Where><Contains><FieldRef Name='Item_x0020_Description' /><Value Type='Note'>" + userInput + "</Value></Contains></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Topic_x002d_' /><FieldRef Name='Item_x0020_Description' /></ViewFields><QueryOptions /></View>" };
var r = list.GetItems(q);
ctx.Load(r);
ctx.ExecuteQuery();
if (r.Count != 0)
{
var searchResults = new DataTable();
searchResults.Columns.AddRange(new[]
{
new DataColumn("ID"), new DataColumn("Document Number"), new DataColumn("Item Description"), new DataColumn("Topic")});
foreach (var oListItem in r)
{
searchResults.Rows.Add(oListItem["ID"], oListItem["Title"], oListItem["Item_x0020_Description"],
oListItem["Topic_x002d_"]);
}
if (dataGridView1 != null)
{
dataGridView1.DataSource = searchResults;
dataGridView1.Refresh();
dataGridView1.Columns[2].DefaultCellStyle.Format = "dd'/'MM'/'yyyy";
var dataGridViewColumn = dataGridView1.Columns["ID"];
if (dataGridViewColumn != null)
dataGridViewColumn.Visible = false;
}
else
MessageBox.Show("after else statement");
}
}
MessageBox.Show("after sharepoint if statement");
return;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("a cell was clicked");
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
MessageBox.Show("starting routine");
if (dataGridView1.SelectedCells.Count > 0)
{
int selectedrowindex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedrowindex];
string a = Convert.ToString(selectedRow.Cells["Document Number"].Value);
MessageBox.Show(a);
textBox2.Text = ("The var =" + a);
}
else MessageBox.Show("if did not end up true");
}
}
}
I failed to initialize these, after adding them to the form method...poof everything works! :
public Form1()
{
InitializeComponent();
dataGridView1.CellClick += dataGridView1_CellClick;
dataGridView1.SelectionChanged += dataGridView1_SelectionChanged;
}
Every time when I click the button only one row will be displayed. But it should show multiple rows. I declare the list after the constructor invoke. I tried with gridview.update() and gridview.refresh() but they didn't work. I could not findout the issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using JournalEntryApp.Model;
namespace JournalEntryApp
{
public partial class NewDocument : Form
{
public NewDocument()
{
InitializeComponent();
}
List<JEFrom> JEFromsList = new List<JEFrom>();
List<JETo> JETosList = new List<JETo>();
JEFrom _jef = null;
private void NewDocument_Load(object sender, EventArgs e)
{
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
private void addToListButton_Click(object sender, EventArgs e)
{
if (string.Empty== fromAccountTextBox.Text)
{
MessageBox.Show("From Account can not be empty!!!");
}
else if (string.Empty == toAccountTextBox.Text)
{
MessageBox.Show("To Account can not be empty!!!");
}
else
{
_jef = new JEFrom{ FromEntryName= fromAccountTextBox.Text , FromEntryDate= DateTime.Now };
JEFromsList.Add(_jef);
temporaryDataGridView.DataSource = JEFromsList;
fromAccountTextBox.Text = string.Empty;
toAccountTextBox.Text = string.Empty;
}
}
}
}
The temporaryDataGridView cannot detect that you have changed the DataSource. It will only refresh when Datasource has changed.
temporaryDataGridView.DataSource = null;
temporaryDataGridView.DataSource = JEFromsList;
so change the Datasource null first.
Or you can use bindingSource
private void NewDocument_Load(object sender, EventArgs e)
{
this.bindingSource1.DataSource = JEFromsList;
temporaryDataGridView.DataSource = this.bindingSource1;
label4.Text = DateTime.Now.ToString("dd-MMM-yyyy");
using (var db =new JournalContext())
{
unitComboBox.DataSource = db.Units.ToList();
unitComboBox.ValueMember = "Id";
unitComboBox.DisplayMember = "UnitName";
}
}
in button_click
JEFromsList.Add(_jef);
bindingSource1.ResetBindings(true);
First post on this wonderful site so feedback is greatly appreciated.
I followed a video instruction on Youtube by one of the NAV guru about consuming web services using C#. I was able to replicate what he did in Sandbox, but now that I want to implement in Live it's a hit or miss type of ordeal. If I made a small change somewhere the WS stopped working then after tweaking it here and there all of a sudden it works, then the cycle continues.
I basically created a form with two datagrids, one for sales header and one for sales line, with 3 buttons for New Order, New Line, and Save. Below is my code. Can you point me in the right direction as to:
1. Why my code is not working?
2. Why it works and then stops working? What to watch out for?
3. In my original code, using System.Data is not showing an error. I had to comment it out on this form because it has the scribbly line underneath. How come?
I am a noob to web services and C# in general. Thanks in advance for your help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SalesOrderXML.ServiceReference3;
using System.ServiceModel;
using System.Net;
namespace SalesOrderXML
{
public partial class Form2 : Form
{
private Sales saleslive = new Sales();
private SalesOrderService_PortClient svc1;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//BasicHttpBinding SalesOrderService_Binding = new BasicHttpBinding();
//SalesOrderService_Binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
//SalesOrderService_Binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var binding = new System.ServiceModel.BasicHttpBinding();
binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
svc1 = new SalesOrderService_PortClient(
//SalesOrderService_Binding, new EndpointAddress("http://localhost:7047/DynamicsNAV/WS/Cronus%20-%20LIVE%20COMPANY/Codeunit/SalesOrderService"));
binding, new EndpointAddress("http://localhost:7047/DynamicsNAV/WS/Cronus%20-%20LIVE%20COMPANY/Codeunit/SalesOrderService"));
svc1.ClientCredentials.Windows.ClientCredential = new NetworkCredential("testuser", "password123", "localhost");
svc1.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
//SalesOrderService_Binding.MaxReceivedMessageSize = 99999999;
binding.MaxReceivedMessageSize = 99999999;
binding.MaxBufferSize = 99999999;
saleslive = new Sales();
LoadData();
}
private void dataGridView3_RowEnter(object sender, DataGridViewCellEventArgs e)
{
var orderlive = saleslive.Order[e.RowIndex];
dataGridView4.DataSource = orderlive.Line;
}
private void LoadData()
{
svc1.ReadSalesOrders(ref saleslive);
dataGridView3.DataSource = saleslive.Order;
}
private void SaveData()
{
svc1.SaveSalesOrders(saleslive);
//dataGridview3.DataSource = saleslive.Order;
}
private void button3_Click(object sender, EventArgs e)
{
svc1.SaveSalesOrders(saleslive);
LoadData();
}
private void button1_Click(object sender, EventArgs e)
{
var orderlive = saleslive.Order;
orderlive[orderlive.Count() - 1] = new Order { Line = new Line[] { } };
Array.Resize(ref orderlive, saleslive.Order.Count() + 1);
saleslive.Order = orderlive;
dataGridView3.DataSource = saleslive.Order;
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var orderlive = saleslive.Order[dataGridView3.CurrentRow.Index];
var line = orderlive.Line;
if (line == null)
{
line = new Line[] { };
}
Array.Resize(ref line, line.Count() + 1);
line[line.Count() - 1] = new Line
{
LineDocType = "Order",
LineDocNo = "",
LineNo = (line.Count() * 10000).ToString(),
Type = "Item",
SKU = "0316",
Quantity = "10",
Price = "1200",
Amount = "12000",
LineTotal = "12000"
};
orderlive.Line = line;
dataGridView4.DataSource = line;
}
}
}
This question already has an answer here:
Function call only works when MessageBox.Show() is included?
(1 answer)
Closed 8 years ago.
I try to make simple audio player,
then I try it.
After end of song, the player stopped.
I want to set it automatically and select randomized, at the playlist.
I use URL and a ListBox as playlist..
This is the code snippet at autoplay part:
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (e.newState == 8)
{
Random rnd = new Random();
int nowPlayIndex = rnd.Next(listURLPlayers.Count);
axWindowsMediaPlayer1.URL = listURLPlayers[nowPlayIndex];
axWindowsMediaPlayer1.Ctlenabled = true;
axWindowsMediaPlayer1.Ctlcontrols.play();
listAudio.SelectedIndex = nowPlayIndex;
}
}
But I try it then the URL changed, but not played automatically.
What is wrong with my code?
https://github.com/mudzakkir/MP3Player.git
Please help.
Ok it is now working..
I should use Timer..
My code is now like this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Mp3Player
{
public partial class MediaPlayer : Form
{
string HomeDir;
string[] sPlaylists, sURLs;
List<string> listURLPlayers = new List<string>();
public MediaPlayer()
{
InitializeComponent();
HomeDir = Directory.GetCurrentDirectory();
string[] playlist = File.ReadAllLines("playlist.txt");
foreach (string fileText in playlist)
{
listAudio.Items.Add(fileText);
}
string[] playlistUrl = File.ReadAllLines("playlistURL.txt");
foreach (string fileText in playlistUrl)
{
listURLPlayers.Add(fileText);
}
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
sPlaylists = openFileDialog1.SafeFileNames;
sURLs = openFileDialog1.FileNames;
for (int i = 0; i < sPlaylists.Length; i++)
{
listAudio.Items.Add(sPlaylists[i]);
}
for (int i = 0; i < sURLs.Length; i++)
{
listURLPlayers.Add(sURLs[i]);
}
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter("playlist.txt");
foreach (var item in listAudio.Items)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
SaveFile = new System.IO.StreamWriter("playlistURL.txt");
foreach (var item in listURLPlayers)
{
SaveFile.WriteLine(item);
}
SaveFile.Close();
}
}
private void listAudio_MouseDoubleClick(object sender, MouseEventArgs e)
{
axWindowsMediaPlayer1.URL = listURLPlayers[listAudio.SelectedIndex];
}
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (e.newState == 8)
{
timer1.Enabled = true;
}
}
private void listAudio_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = listURLPlayers[listAudio.SelectedIndex];
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
Random rnd = new Random();
int nowPlayIndex = rnd.Next(listURLPlayers.Count);
axWindowsMediaPlayer1.URL = listURLPlayers[nowPlayIndex];
listAudio.SelectedIndex = nowPlayIndex;
}
}
}
Thank You
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