-4

当我在 C# 中的 datagridview 中添加列时,我想生成动态文本框和标签。我还希望稍后编写一个 SQL 查询,它将我新生成的文本框作为参数/新列名。发生的错误说“参数超出范围异常未处理”。

请帮忙

public void CreateLabels()
    {
        Label lb = new Label();
        this.Controls.Add(lb);
        int p= dataGridView1.ColumnCount;
        for (int k = p; k <= dataGridView1.ColumnCount; k++)
        {
            for (int z =p; z <= dataGridView1.ColumnCount; z++)
            {
                dataGridView1.Refresh();
                lb.Text = dataGridView1.Columns[z++].HeaderText;
            }
            lb.Show();
            lb.Visible = true;
        }
        lb.Location = new Point(m,n=n+25);
        lb.Width = 199;
        lb.Height = 20;
    }
    public void CreateTextBoxes()
    {
        TextBox tb = new TextBox();
        this.Controls.Add(tb);
        for (int i = 5; i <= dataGridView1.ColumnCount; i++)
        {
            dataGridView1.Refresh();
            tb.Name = "textBox" + i;
            MessageBox.Show(tb.Name);
        }
        tb.Location = new Point(x, y = y + 25);
        tb.Show();
        tb.Visible = true;         
    }*/

    //Below  method is used to get data in datagridview1 and to reflect in runtime text boxes and labels;the visible property is kept false 

    /*private void displayRec()
    {
        try
        {
            string str = System.Environment.MachineName;
            SqlConnection sconn = new SqlConnection("Data Source='" + str + "';Initial Catalog=main;Integrated Security=True");
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter("Select * from invent", sconn);
            da.Fill(dt);

            dataGridView1.DataSource = dt.DefaultView;
            //dataGridView1.Refresh();
        }
        catch (Exception e)
        {
            MessageBox.Show(e.ToString());
        }
    }
4

1 回答 1

0

老实说,我不明白你的循环的想法。它们具有相同的条件,您从不使用“k”;
然而,两个循环都从最后一列 +1 开始;并且在 lb.Text 的分配中,您试图获取不存在的列的 HeaderText。这就是为什么你有超出范围的异常。

于 2013-03-07T12:08:51.193 回答