生成动态文本框和标签
本文关键字:标签 文本 动态 | 更新日期: 2023-09-27 18:02:58
我想生成动态文本框和标签,因为我添加列在我的datagridview在c#。我还希望稍后编写一个SQL查询,它将我新生成的textBoxes作为参数/新列名。发生的错误是"参数超出范围异常未处理"。
请帮
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());
}
}
老实说,我不明白你的循环的想法。它们有相同的条件,你从不使用'k';
然而,两个循环都是从最后一列+1开始的;在分配lb.Text时,您试图获取不存在的列的HeaderText。这就是为什么会出现out of range异常