Click here to Skip to main content
15,908,166 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear people

Can someone help me please sort out this problem with DataGridView. On click event button I'm generating into dataGridView two Columns with the Rows provided, using the database query statement (see the code below) and in the mean time I'm adding another 2 columns with the rows at design time.

When I run my application and I click the button it displays correctly the all columns and rows, but when I click again the same button it generates this error:


System.InvalidOpereationException: Provided column already belongs to the DataGridView control.

Here is also the code:

private DataGridViewTextBoxColumn ColQtyStock = new DataGridViewTextBoxColumn();
        private DataGridViewTextBoxColumn ColStatus = new DataGridViewTextBoxColumn();
        
        private void cmdStarters_Click(object sender, EventArgs e)
        {
            
            OleDbConnectionStringBuilder connBuilder = new OleDbConnectionStringBuilder();
            connBuilder.DataSource = @"C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposMenu.accdb";
            connBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            connBuilder.Add("Jet OLEDB:Engine Type", "5");
            // Food SQL Query
            string foodTypeSql = @"SELECT FoodName, FoodType FROM Food WHERE FoodType = @foodType";
            using (OleDbConnection conn = new OleDbConnection(connBuilder.ConnectionString))
            {
                try
                {
                    

                    OleDbCommand foodsCommand = new OleDbCommand(foodTypeSql, conn);
                    OleDbParameter foodType = foodsCommand.Parameters.Add("@foodType", OleDbType.VarChar, 15);
                    OleDbDataAdapter foodsDa = new OleDbDataAdapter(foodsCommand);
                    DataRow dr;
                    DataSet ds = new DataSet();
                    conn.Open();
                    foodType.Value = "Starter";
                    foodsDa.Fill(ds, "Food_table");
                    conn.Close();
                    dataGridView1.DataSource = ds;
                    dataGridView1.DataMember = "Food_table";
                    
                    dataGridView1.Columns.AddRange(ColQtyStock,ColStatus);//new DataGridViewColumn[] {
                    
                    //});
                    
                    DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
                    this.dataGridView1.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;
                    dataGridViewCellStyle1.Font = new Font("Verdana", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

                    DataGridViewCellStyle dataGridViewCellStyle2 = new DataGridViewCellStyle();
                    this.dataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle2;
                    dataGridViewCellStyle2.Font = new Font("Verdana", 18.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    
                    this.dataGridView1.RowTemplate.Height = 60;
                    
                    this.dataGridView1.Columns[0].Width = 500;
                    this.dataGridView1.Columns[1].Width = 200;
                    this.dataGridView1.Columns[2].Width = 300;
                    this.dataGridView1.Columns[3].Width = 200;

                    // ColStatus 
                    ColStatus.HeaderText = "Status";
                    ColStatus.Name = "ColStatus";

                    // ColQtyStock
                    ColQtyStock.HeaderText = "Quantity In Stock";
                    ColQtyStock.Name = "ColQtyStock";
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex);
                }
            }

        }



Could someone tell me what am I doing worng please...


thanks in advance

roni
Posted

It seems like you are using DataGridView control's AutoGenerateColumns=True.

Solution 1:
- Set AutoGenerateColumns = False.
- Create columns from designer or Form Loaded event

Solution 2:
- Call
dataGridView1.Columns.Clear()

on the Button Click event.

Mark it as answer, if it is helpful
 
Share this answer
 
v2
You are adding the columns in the click handler and if you click twice you are going to add these columns again, hence the error. I think the error message is pretty clear about that.

Please also look into OleDBCommand and the use or Parameters with it. MSDN documentation clearly states that named parameters cannot be used with when command type is Text (SQL). Your code setting the parameters works because you only have on parameter, but you'll run into problems when there is more than one parameters and the sequence you fill them into the parameters collection differs from the sequence of those parameters in your SQL.

Modification:
The code where you create the two columns:
C#
private DataGridViewTextBoxColumn ColQtyStock = new DataGridViewTextBoxColumn();
private DataGridViewTextBoxColumn ColStatus = new DataGridViewTextBoxColumn();

is outside your click handler. Inside your handler you can add them once but the second time must fail, because they are already added!

Best Regards,
Manfred
 
Share this answer
 
v4
Comments
LAPEC 2-Jan-11 18:52pm    
Hi Manfred

So are you saying that the two lines of code (you mentioned) I should place them inside my event handler...

kind regards


roni
LAPEC 2-Jan-11 18:59pm    
Now I'm facing much more (a bigger problem), I have never thought of that what you said earlier...
deep deep trouble :(

kind regards
Manfred Rudolf Bihy 2-Jan-11 19:14pm    
If you place the instantiations of the columns inside the event handler you would be adding two new columns to your grid every time you clicked. That can hardly be what you are trying to achieve, or is it. Think about it! What exactly are you trying to accomplish?
LAPEC 2-Jan-11 19:39pm    
I already done that but its not working and it creates more problem.
What I'm trying to accomplish is (as I said earlier when I posted my question), get the database records using parameter (see the code above) display them into datagridview, and in the mean time create another two columns at the run time and aswell display this other two columns together with the other ones. like so...
________________________________________________________________
FoodName ToodType Quantity In Stock Status
----------------------------------------------------------------
Soup Starter 0 Allways in Stock
Olives Starter 0 Allways in Stock

________________________________________________________________

Kind regards

Roni
Manfred Rudolf Bihy 2-Jan-11 20:55pm    
I ask one last time. Why do you deem it nescessary to add these two columns every time you clicked the button?
They should be added once and that's it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900