mardi 13 février 2018

Is there a way to programmatically call a checkbox and a column in a DataGridView?

I am making an Excel Validation Program. Once imported, each columns would be validated if they are decimals.

enter image description here

The checkboxes are made dynamically and represents the columns in a datatable per tabs (tabs are sheets from an Excel File) using this code:

int dynamicHeight = 0;
            int padding = 10;

            CheckBox[] chk = new CheckBox[dt.Columns.Count];

            for (int i = 0; i <= dt.Columns.Count - 1; i ++)
            {


                chk[i] = new CheckBox();
                chk[i].Name = dt.Columns[i].ColumnName;
                chk[i].Text = dt.Columns[i].ColumnName;
                chk[i].AutoCheck = true;
                chk[i].Bounds = new Rectangle(10, 20 + padding + dynamicHeight, 40, 22);
                panelCol.Controls.Add(chk[i]);
                dynamicHeight += 20;
                panelCol.Size = new Size(120, dynamicHeight);
                panelCol.Controls.Add(chk[i]);
                chk[i].Location = new Point(0, dynamicHeight);
                chk[i].Size = new Size(120, 21);
                panelCol.BackColor = Color.White;
                panelCol.AutoScroll = true;
                //panelCol.AutoScrollMinSize = new Size (0, 1200);


            }

I want to call them but dynamically too. What I am doing is manually presetting every checkbox like this:

 chk[0].CheckedChanged += (s, e) =>
            {
                decimal num;
                if (chk[0].Checked == true && chk[0].Name.Contains(dt.Columns[0].ColumnName))
                {
                    //MessageBox.Show("HELLOW WORLD " + 0);

                    for (int i = 0; i < dataGridView1.RowCount; i++)
                    {
                        if (!Decimal.TryParse(dataGridView1.Rows[i].Cells["January"].Value.ToString(), out num))
                        {
                            if (dataGridView1.Rows[i].Cells[dt.Columns["January"].ColumnName].Value.ToString() == null || dataGridView1.Rows[i].Cells[dt.Columns["January"].ColumnName].Value.ToString() == "")
                            {

                            }
                            else
                            {
                                MessageBox.Show(dataGridView1.Rows[i].Cells["January"].Value.ToString() + "  NOT A DECIMAL!");
                            }

                        }
                        else
                        {

                        }
                    }
                }
            };

Is there a fix or solution for this so that I don't have to preset them all manually? Cause what if an excel file has a different column name that would mean presetting new columns again.




Aucun commentaire:

Enregistrer un commentaire