JaSk
JaSk

Reputation: 107

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

}

Upvotes: 1

Views: 255

Answers (3)

kubal5003
kubal5003

Reputation: 7254

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

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064114

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

Upvotes: 0

kubal5003
kubal5003

Reputation: 7254

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)

Upvotes: 1

Related Questions