Hy,
i'm working on a application and i'm using a datagridview for displaying 2 columns:example: name of product and quantity. when i select a product and a quantity , pressing an ADD button this datagridview should displaying them...i've tried in this way

 private void adaugareGrid()
        {
            dataGridView1.Refresh();
            index = this.dataGridView1.Rows.Count;
            dataGridView1.ColumnCount = 2;
            dataGridView1.Columns[0].Name = "Detalii Produs";
            dataGridView1.Columns[1].Name = "Cantitate";
            this.dataGridView1.Rows.Add();
            this.dataGridView1.Rows[index].Cells[0].Value = txtModel.Text.ToString();
            this.dataGridView1.Rows[index].Cells[1].Value = txtCantitate.Text.ToString();
           index++;
            }

but after one row is adding then i get an error because of that index..i really don't undersand why.could you please help me?

Recommended Answers

All 3 Replies

Try this, no index needed here:

string[] Arow = { "model1", "candidate1"};
dataGridView1.Rows.Add(Arow);

Apparently you add data to dgv control from textBoxes. Every time you insert something into textBoxes, these data (2) have to insert into a new row in dgv.
This is how you do it:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            dataGridView1.Columns.Add("col1", "column 1");
            dataGridView1.Columns.Add("col2", "column 2");
            dataGridView1.AllowUserToAddRows = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string a = textBox1.Text;
            string b = textBox2.Text;
            int allRows = dataGridView1.Rows.Count;
            if (a != String.Empty || b != String.Empty)
            {
                dataGridView1.Rows.Add(a, b);
                textBox1.Text = "";
                textBox2.Text = "";
            }
        }
    }

You can even shortan the code (like ddanbe proposed):

private void button1_Click(object sender, EventArgs e)
        {
            string[] values = new string[] { textBox1.Text, textBox2.Text };
            int allRows = dataGridView1.Rows.Count;
            if (values[0] != String.Empty || values[1] != String.Empty)
            {
                dataGridView1.Rows.Add(values);
                textBox1.Text = "";
                textBox2.Text = "";
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.